When working with strings in Kotlin, sometimes you might encounter scenarios where a multiline string would serve better for your use case. Kotlin addresses this with what's called raw strings. These are wrapped in triple quotes (""") and they retain formatting such as newlines and indentations without the need for escape characters.
Declaration of Multiline Strings
Let's start by showing how to declare a basic multiline string in Kotlin:
fun main() {
val multilineString = """
This is a
multiline string
in Kotlin.
"""
println(multilineString)
}
The output of this snippet would be:
This is a
multiline string
in Kotlin.
Note how the newlines and spaces are preserved. The raw string ignores leading spaces on each line to maintain indentation from the body of the code.
Trimming Indentations
If you want to trim the preceding blank spaces generated by indentation, you can make use of the trimMargin() or trimIndent() functions.
Using trimMargin()
The trimMargin() function removes whitespace before a delimiter and the delimiter itself. By default, the delimiter is |.
fun main() {
val text = """
|This is line 1
|This is line 2
|This is line 3
""".trimMargin()
println(text)
}
The output will be:
This is line 1
This is line 2
This is line 3
The trimMargin() function is particularly handy when you want to remove leading whitespace but maintain alignment in the code.
Using trimIndent()
The trimIndent() function is used to remove the leading whitespace from each line so that the minimum common sequence is determined and removed.
fun main() {
val text = """
Quick brown fox
jumps over the lazy dog.
Keele code example.
""".trimIndent()
println(text)
}
The output will be:
Quick brown fox
jumps over the lazy dog.
Keele code example.
Combining Multiline Strings
Sometimes, you might want to combine multiple multiline strings together. Simply use the string concatenation operator +:
fun main() {
val part1 = """
Hello,
this is part 1.
"""
val part2 = """
And this is part 2.
"""
val combined = part1 + part2
println(combined)
}
The output will be:
Hello,
this is part 1.
And this is part 2.
Notice that concatenation maintains the formatting of each string. Multiline strings are flexible and make handling complex string formats more readable and manageable. By using the techniques covered in this article, you can effectively utilize multiline strings in Kotlin for your projects.