Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 08 / Topic 5 of 7

Simple structured text: a comma-separated format

Before reaching for a real CSV or JSON library (not yet available in Stage 1 -- no Gradle, no third-party dependency), a surprising amount of real work is just "one record per line, fields joined by a delimiter". joinToString builds a row; split parses one back.

// a plain class from Part 7 -- data class arrives in Stage 2, Part 9
class Order(val id: String, val item: String, val quantity: Int, val price: Double) {
    fun toCsvLine(): String = listOf(id, item, quantity.toString(), price.toString()).joinToString(",")
}

fun parseOrderLine(line: String): Order {
    val fields = line.split(",").map { it.trim() }
    require(fields.size == 4) { "expected 4 fields, got ${fields.size} in \"$line\"" }
    return Order(
        id = fields[0],
        item = fields[1],
        quantity = fields[2].toInt(),
        price = fields[3].toDouble()
    )
}
val orders = listOf(
    Order("O-1001", "Rice (kg)", 5, 68.0),
    Order("O-1002", "Dal (kg)", 2, 145.0),
    Order("O-1003", "Atta (kg)", 10, 52.0)
)

val ordersFile = File("orders.csv")
val header = "id,item,quantity,price"
val lines = listOf(header) + orders.map { it.toCsvLine() }
ordersFile.writeText(lines.joinToString("\n") + "\n")

println("--- orders.csv ---")
print(ordersFile.readText())

val parsed = ordersFile.readLines().drop(1).map { parseOrderLine(it) }
println("--- parsed back ---")
for (order in parsed) {
    val total = order.quantity * order.price
    println("${order.id}: ${order.quantity} x ${order.item} @ ₹${order.price} = ₹$total")
}

val grandTotal = parsed.sumOf { it.quantity * it.price }
println("Grand total: ₹$grandTotal")
--- orders.csv ---
id,item,quantity,price
O-1001,Rice (kg),5,68.0
O-1002,Dal (kg),2,145.0
O-1003,Atta (kg),10,52.0
--- parsed back ---
O-1001: 5 x Rice (kg) @ ₹68.0 = ₹340.0
O-1002: 2 x Dal (kg) @ ₹145.0 = ₹290.0
O-1003: 10 x Atta (kg) @ ₹52.0 = ₹520.0
Grand total: ₹1150.0

.drop(1) skips the header line before parsing; require(fields.size == 4) rejects a malformed row the same way Part 7's init blocks rejected a bad constructor argument.

⚠️ The naive part, called out honestly: splitting on "," breaks the moment a field's own value contains a comma -- "Rice, 1kg pack" would split into two fields, not one. Real CSV libraries handle quoted fields with embedded commas; this part deliberately stays with delimiter-splitting on data that doesn't contain the delimiter, since that's genuinely how far split/joinToString can safely go on their own.

Full program: examples/05_structured_text.kt.

Done here? The practice set for Part 8 — including the solutions — is on the part page.

Search the guide