String Construction in Kotlin - String Templates vs. StringBuilder and buildString

String templates, joinToString(), and buildString provide powerful and idiomatic approaches for string construction in Kotlin. By utilizing these tools effectively, you can enhance the readability, maintainability, and overall quality of your Kotlin code.

Bram Yeh
2 min readNov 4, 2023

TL;DR

Key Considerations

  • String templates are the preferred choice for simple string construction.
  • StringBuilder can be used for complex string manipulation but is not considered idiomatic.
  • joinToString() is the preferred method for generating strings from collections.
  • buildString is a convenient inline function for concise string manipulation.

String Templates: The Preferred Choice

In general, Kotlin programmers favor string templates over string concatenation or String.format(). String templates offer a concise and readable syntax for embedding expressions directly into strings. This approach simplifies code readability and maintenance

StringBuilder: An Alternative for Complex String Manipulation

While string templates are generally preferred, there may be instances where you need to generate strings from collections or iterators. In these cases, some programmers might resort to using a StringBuilder object. This approach is functional but not considered idiomatic in Kotlin.

joinToString(): A More Idiomatic Option for Collection-Based String Generation

A more preferred solution for generating strings from collections involves utilizing the joinToString() function. This function eliminates the need for explicit string concatenation or StringBuilder manipulation, resulting in cleaner and more concise code:

val greekAlphabet = listOf(“Alpha”, “Beta”, “gamma”)
val contents =
"""
Alphabet:
${greekAlphabet.joinToString("\n")}
"""

The joinToString() function not only simplifies the code but also enhances its readability. It clearly conveys the intention of combining the elements of the contents list into a formatted string with the specified delimiter.

buildString: An Inline Function for Convenient String Manipulation

Kotlin’s standard library provides an inline function called buildString that simplifies the use of StringBuilder. It accepts a lambda argument that grants access to an underlying StringBuilder instance referred to as this. Within this lambda, you can directly invoke methods like append without explicitly specifying the receiver.

Additionally, buildString automatically handles the process of constructing the final string. This approach enables you to write more concise and functional code for string manipulation.

// the code isn't complecated enough.. it's just a sample
val greekAlphabet = listOf("Alpha", "Beta", "gamma")
val contents = buildString {
appendLine("Alphabet:")
greekAlphabet.forEach { appendLine("$it") }
}

In general, it’s recommended to favor buildString over StringBuilder directly. Because

Reduced Error Proneness: It eliminates the potential for inadvertently reusing the wrong StringBuilder variable or neglecting to call toString() at the end.

  1. Idiomatic Kotlin Syntax: It aligns with Kotlin’s idiomatic style by utilizing the trailing lambda syntax.
  2. Conciseness: It promotes more concise and readable code.

Conclusion

String templates, joinToString(), and buildString provide powerful and idiomatic approaches for string construction in Kotlin. By utilizing these tools effectively, you can enhance the readability, maintainability, and overall quality of your Kotlin code.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Bram Yeh
Bram Yeh

Written by Bram Yeh

Lead Android & iOS Mobile Engineer at Yahoo (Verizon Media) Taiwan https://www.linkedin.com/in/hanruyeh/

No responses yet

Write a response