DEV Community

Cover image for [Tiny] Nice Way to Build Strings in Kotlin
Petr Filaretov
Petr Filaretov

Posted on • Edited on

1

[Tiny] Nice Way to Build Strings in Kotlin

One nice way to build a String in Kotlin is the buildString() top-level function. It takes a lambda as an argument, and within that lambda, you can use various append methods on a StringBuilder instance to construct a string.

Once the lambda is executed, the resulting StringBuilder object is converted to a regular String object.

Here is a sample:

private const val AGE_LENGTH = 4
private const val NAME_LENGTH = 14
private const val TABLE_LENGTH = 40

data class Person(val name: String, val age: Int, val motherland: String)

fun generateReport(people: List<Person>) = buildString {
    appendLine("Report:")
    appendLine("".padEnd(TABLE_LENGTH, '-'))

    appendLine("${"Name".padEnd(NAME_LENGTH)} | ${"Age".padEnd(AGE_LENGTH)} | Motherland")
    appendLine("".padEnd(TABLE_LENGTH, '-'))

    people.forEach {
        appendLine("${it.name.padEnd(NAME_LENGTH)} | ${it.age.toString().padEnd(AGE_LENGTH)} | ${it.motherland}")
    }
    appendLine("".padEnd(TABLE_LENGTH, '-'))
}

fun main() {
    val people = listOf(
        Person("Frodo Baggins", 33, "The Shire"),
        Person("Gandalf", 2019, "Middle-earth"),
        Person("Aragorn", 87, "Gondor"),
        Person("Legolas", 2931, "Woodland Realm"),
        Person("Gimli", 139, "Lonely Mountain"),
    )

    val report = generateReport(people)
    println(report)
}
Enter fullscreen mode Exit fullscreen mode

The output of the above code will be:

Report:
----------------------------------------
Name           | Age  | Motherland
----------------------------------------
Frodo Baggins  | 33   | The Shire
Gandalf        | 2019 | Middle-earth
Aragorn        | 87   | Gondor
Legolas        | 2931 | Woodland Realm
Gimli          | 139  | Lonely Mountain
----------------------------------------
Enter fullscreen mode Exit fullscreen mode

Dream your code, code your dream.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay