Kotlin Koans BR: Triple-quoted strings
By Rodrigo Sicarelli 1 min read
🔗 Task
Swap the trimIndent call for the trimMargin call, setting # as the prefix value, so the resulting string won’t contain the prefix character.
There are functions like trimIndent and trimMargin that format multi-line triple-quoted strings to fit the surrounding code context.
Use case
In Kotlin, triple-quoted strings (multiline strings) make it easy to represent strings with several lines and special characters, without having to escape them.
This technique improves code clarity and simplifies working with long text or text with intricate structures.
By using a pair of triple quotes """ """, you can declare a multi-line piece of text in Kotlin.
val text = """
This is a string that contains
several lines
without needing escape characters.
"""
In this context, sequences like \n (new line) and \t (tab) are read literally as text, without any
special handling.
Advantages
- Simplicity: easy to work with long text or text that needs specific formatting.
- No character escaping needed: special characters don’t have to be “escaped”, which improves the clarity and readability of the code.
- They act as a kind of string template, making it easy to embed dynamic values in text and giving you more flexibility when working with strings.
Disadvantages
- Unwanted whitespace can be avoided by using functions like
trimMargin()andtrimIndent()to remove those extra spaces. - Less support in some IDEs: although it’s rare, some IDEs and text editors may struggle with syntax highlighting or automatic formatting.
- Performance concerns: in some situations, such as heavy loops, overusing them can lead to performance problems.
Analogy
Triple-quoted strings in Kotlin are like murals on walls. A mural isn’t interrupted by frames or borders, letting the art stretch across the whole surface without a break.
val heart = """
,d88b.d88b,
88888888888
`Y8888888Y'
`Y888Y'
`Y'
"""