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)
}
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
----------------------------------------
Dream your code, code your dream.
Top comments (0)