CodeGym /課程 /Kotlin SELF /Output formatting

Output formatting

Kotlin SELF
等級 27, 課堂 1
開放

1. Introduction

When a program is just learning to walk, it’s enough to do println("OK"). But the further you go with your console project, the more often an “internal user” shows up — you yourself after 20 minutes of debugging. And right here you suddenly find out that “whatever output” turns any check into archaeology: you’re trying to figure out what total=1200 means, why there is no currency next to it, and where the record boundaries are at all.

Formatting is not about beauty; it’s about a contract between your code and a person: what counts as a header, what is a data row, where a number is, where text is, which fields are “columns”, and what to do if a string is longer than expected. Plus, good formatting often helps reveal bugs: for example, if the totals column “shifts”, it means somewhere you unexpectedly got text instead of a number.

To keep everything practical, we’ll continue our hypothetical console project “expense tracking”. It’s still without classes, so we’ll store expenses as Triple(category, amount, note).

2. String interpolation: $x and ${expr}

String interpolation in Kotlin is when you insert a value directly inside a string: $x for a simple name and ${expr} for an expression. It’s a basic thing, but it’s exactly what most often makes output readable without extra + and without “gluing things together with duct tape”.

It’s important to feel the difference: concatenation via + literally glues chunks together, while string templates let you write almost “human text” with substitutions. For reports and user-facing messages, this almost always wins.

Basic example: print an expense

Let’s start simple. Suppose an expense is Triple<String, Int, String>: category, amount, comment.

fun main() {
    val expense = Triple("food", 450, "coffee and croissant")

    val category = expense.first
    val amount = expense.second
    val note = expense.third

    println("Expense: category=$category, amount=$amount, note=\"$note\"")
    // Expense: category=food, amount=450, note="coffee and croissant"
}

Notice the quotes around note: it’s a small thing, but sometimes it helps visually see where the text starts and ends.

When you need ${expr}

Sometimes you want to embed the result of a computation. For example, show an amount with a sign or calculate tax.

fun main() {
    val amount = 450
    val tax = (amount * 0.2).toInt()

    println("Amount=$amount, tax(20%)=$tax, total=${amount + tax}")
    // Amount=450, tax(20%)=90, total=540
}

Here you can see why curly braces are needed: inside ${...} you can write an expression.

About readability: don’t turn a string into a “dissertation”

A good heuristic is this: if an expression inside a string takes three lines, it’s time to move the computation into a separate val. In other words, formatting should not hide logic. Kotlin lets you insert “anything”, but you’re writing code not only for the compiler, but also for your future self.

3. Separate “compute” and “display”

One common beginner problem: computations, parsing, and printing get mixed into one salad. Does it work? Sometimes. Is it clear? Usually not. If you’ve ever debugged a program by its output, you know: the “cleaner” the stages are separated, the easier it is to notice a mistake.

Let’s stick to a discipline: functions that compute return data, and functions that format return a string. And then main() decides whether to print it or not. This makes the program more predictable and easier to test (even if we haven’t studied testing yet — the principle is still useful).

Format one line with a separate function

fun formatExpense(expense: Triple<String, Int, String>): String {
    val category = expense.first
    val amount = expense.second
    val note = expense.third

    return "[$category] $amount — $note"
}

fun main() {
    val e = Triple("transport", 120, "metro")
    println(formatExpense(e)) // [transport] 120 — metro
}

Notice: formatExpense prints nothing, it only returns a string. This is a small but very important style.

Formatting and logging are different things

In console learning projects, you want to print everything. That’s normal at the start. But that’s exactly why it’s useful to get used to this now: “formatting” is about a message to the user or a report, not about chaotic println("x=$x") in the middle of an algorithm.

4. Column alignment: padEnd() and padStart()

When there’s more than one field, “one line with commas” quickly becomes unreadable. The human eye likes columns: text on the left, numbers on the right. In a GUI, a table does this; in the console — spaces. And this is where Kotlin offers a very friendly tool: padEnd(width) and padStart(width).

The idea is simple: a string is padded with spaces to the desired width. padEnd adds spaces to the right, padStart — to the left. And yes, it sounds like “just spaces”, but these are the spaces that suddenly save you a ton of nerves.

Mini-table: header and one row

fun main() {
    val nameW = 12
    val amountW = 8

    val header = "CATEGORY".padEnd(nameW) + "AMOUNT".padStart(amountW)
    val row = "food".padEnd(nameW) + "450".padStart(amountW)

    println(header)
    // CATEGORY       AMOUNT
    println(row)
    // food             450
}

An important point here: for now, we output numbers as strings "450".

The difference between padEnd and padStart

Sometimes it’s easier to see it:

Method Where it adds spaces Typical use case
padEnd(width)
to the right text column on the left
padStart(width)
to the left numeric column on the right

In the console, numbers are usually right-aligned, because it’s easier to compare magnitudes, especially when lengths differ: 5, 50, 5000.

Align numbers: first toString(), then padStart()

A common micro-mistake: trying to call padStart on a number directly. padStart is a string method, so the number must be turned into a string.

fun main() {
    val amount = 450
    val amountW = 8

    val cell = amount.toString().padStart(amountW)
    println("|$cell|") // |     450|
}

It looks funny, but |...| really helps you see the spaces.

Why widths are better stored in variables

If you set width to 10 in one place and 12 in another, columns will “shift”. So it’s better to agree: widths are a small formatting configuration.

fun main() {
    val categoryW = 14
    val amountW = 8

    val cat = "transport".padEnd(categoryW)
    val amt = 120.toString().padStart(amountW)

    println(cat + amt) // transport        120
}

If text is longer than the width

padEnd does not cut the string; it only pads. If the category comes in with length 50 characters, it will simply push everything to the right. In the console this looks like “formatting broke”. So sometimes a rule is introduced: “if it’s longer — we cut it”.

We’re not using anything “advanced” yet — only what is already familiar: length and substring.

fun fitLeft(text: String, width: Int): String {
    val cut = if (text.length > width) text.substring(0, width) else text
    return cut.padEnd(width)
}

fun main() {
    val w = 10
    println(fitLeft("very-very-long-category", w) + "|") // very-very-|
}

Yes, the word got cut. That’s okay: a console table is not elastic. The main thing is that the rule is now explicit and consistent everywhere.

5. Multi-line output: joinToString() and raw strings

When you print a report, you usually have a set of lines: header, separator line, data rows, total. The most straightforward way is lots of println(...). But there is a cleaner idea: build a list of lines, and then join them into one multi-line text.

joinToString(...) is great for this: it turns a collection of elements into one string with a separator, prefix, postfix, and other settings. And if you make the separator "\n", you get multi-line text.

Build a report as List<String>

fun main() {
    val lines = listOf(
        "CATEGORY".padEnd(12) + "AMOUNT".padStart(8),
        "------------" + "--------",
        "food".padEnd(12) + "450".padStart(8),
        "transport".padEnd(12) + "120".padStart(8)
    )

    val report = lines.joinToString(separator = "\n")
    println(report)
}

The key idea here: first you get the “logical report lines”, and then you glue them into the final text. This is easier to maintain than ten println calls mixed with computations.

prefix and postfix for decoration

joinToString can add a prefix and postfix, which is sometimes convenient for styling.

fun main() {
    val rows = listOf("A", "B", "C")
    val text = rows.joinToString(
        separator = "\n",
        prefix = "Report:\n",
        postfix = "\n(end)"
    )
    println(text)
    // Report:
    // A
    // B
    // C
    // (end)
}

Prefix and postfix are not “formatting magic”; they’re just two more pieces of a string. But when the standard function provides them, there’s less chance to make a mistake.

Multi-line strings """...""" as a template

Sometimes it’s more convenient not to assemble a report from many small pieces, but to have a multi-line “template” — like a form. Kotlin has raw strings for this: triple quotes """...""".

The advantage is that inside you can freely write quotes and line breaks, and it’s also convenient to use trimIndent() to format indentation nicely in code but not carry it into the output.

fun main() {
    val title = "Expenses report"
    val header = """
        === $title ===
        Columns: category | amount | note
    """.trimIndent()

    println(header)
    // === Expenses report ===
    // Columns: category | amount | note
}

Notice: we still use $title. A raw string doesn’t cancel string templates — it just makes line breaks natural.

6. Practical example: an expenses report

Now let’s make a small practical part for our expense-tracking project: a function that takes a list of expenses and returns a nicely formatted report text. We’ll use only what we’ve discussed: string templates, padStart/padEnd, building lines into a list, and joinToString("\n").

Expense data is still Triple(category, amount, note). Yes, Triple is not the most convenient type in the world, but it honestly works until we move on to classes.

Formatting one table row

fun formatExpenseRow(
    expense: Triple<String, Int, String>,
    categoryW: Int,
    amountW: Int
): String {
    val category = expense.first
    val amount = expense.second
    val note = expense.third

    val safeCategory = if (category.length > categoryW) category.substring(0, categoryW) else category
    val catCell = safeCategory.padEnd(categoryW)
    val amountCell = amount.toString().padStart(amountW)

    return "$catCell$amountCell  $note"
}

Here we made two “contracts”: the category width and the amount width. And we also noticed the “dangerous spot” — a long category — and decided in advance to cut it.

Full report as one multi-line string

fun buildExpensesReport(expenses: List<Triple<String, Int, String>>): String {
    val categoryW = 14
    val amountW = 8

    val title = "EXPENSES"
    val header = "CATEGORY".padEnd(categoryW) + "AMOUNT".padStart(amountW) + "  NOTE"
    val separator = "-".repeat(categoryW) + "-".repeat(amountW) + "  ----"

    val rows = expenses.map { e ->
        formatExpenseRow(e, categoryW, amountW)
    }

    val total = expenses.sumOf { it.second }
    val footer = "TOTAL".padEnd(categoryW) + total.toString().padStart(amountW)

    val lines = listOf(
        "== $title ==",
        header,
        separator
    ) + rows + listOf(separator, footer)

    return lines.joinToString(separator = "\n")
}

There are several important observations here.

First, we don’t print anything inside buildExpensesReport. We return a string — it’s more convenient than “printing along the way”. Second, we explicitly fix the column widths and use them consistently everywhere. Third, the report is built as a list of lines, and at the end it is turned into multi-line text via joinToString("\n").

Using it in main()

fun main() {
    val expenses = listOf(
        Triple("food", 450, "coffee and croissant"),
        Triple("transport", 120, "metro"),
        Triple("books", 900, "kotlin book")
    )

    val report = buildExpensesReport(expenses)
    println(report)
    // == EXPENSES ==
    // CATEGORY         AMOUNT  NOTE
    // ------------------------  ----
    // food               450  coffee and croissant
    // transport          120  metro
    // books              900  kotlin book
    // ------------------------  ----
    // TOTAL             1470
}

If you’re thinking now “this looks like a tiny terminal UI”, then yes — that’s exactly how console reports are born: from spaces, discipline, and a bit of paranoia about widths.

7. Common mistakes

Mistake #1: mixing computation and printing in one place until the code turns into “spaghetti”.
Beginners often do this: computed the sum — immediately println, then in the middle of the loop another println, then somewhere in an if too. As a result, you can’t reuse the output, can’t assemble a report into a string, and it’s hard to verify correctness. The cure is a habit: the formatting function returns a String, and printing lives in one or two places.

Mistake #2: expecting padStart/padEnd to “figure out by itself” how to align a number.
padStart works with a string, not a number. So the “correct ritual” is: amount.toString().padStart(width). If you forget toString(), you either get a compile error or start inventing strange workarounds.

Mistake #3: not fixing column widths and scattering numbers 10, 12, 8 throughout the code.
At first it seems “obvious enough”. Then you change the header width in one place, and the data rows in another — and the table falls apart. It’s much more reliable to have val categoryW = ..., val amountW = ... and use them as a mini configuration for the report.

Mistake #4: not thinking about long strings, causing the whole table to “shift”.
padEnd does not cut a string. If a category suddenly contains 40 characters, it will move the other columns, and the report becomes unreadable. You need to choose a policy in advance: cut (substring), shorten with ellipsis, or wrap to the next line. For a learning version, a simple “cut to width” is enough.

Mistake #5: building a multi-line report with dozens of println calls, and then being surprised that the format is hard to change.
When the report is created as a single string via joinToString("\n"), you can easily save it, return it from a function, show it partially, or add content above/below. When the report is printed “as you go”, you lose control.

1
任務
Kotlin SELF, 等級 27, 課堂 1
上鎖
工作階段狀態
工作階段狀態
1
任務
Kotlin SELF, 等級 27, 課堂 1
上鎖
玩家記分板
玩家記分板
1
任務
Kotlin SELF, 等級 27, 課堂 1
上鎖
分類欄
分類欄
1
任務
Kotlin SELF, 等級 27, 課堂 1
上鎖
應用程式橫幅
應用程式橫幅
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION