Building Strings with Kotlin

Creating new Strings in any JVM language is often slow and memory extensive. To prevent this, StringBuilders are introduced. To use them in Kotlin, Kotlin introduced the buildString method. This is especially helpful when building bigger Strings.

val result = buildString {
    append("Lucky numbers: ")
    for (i in 1..10) {
        append("${(Math.random() * 100).toInt()}, ")
    }
}

fun main(args: Array<String>) {
    println(result)
}

Output:

Lucky numbers: 37, 92, 47, 34, 33, 92, 98, 82, 51, 5,

Leave a Reply

Your email address will not be published. Required fields are marked *