Working with text
We've already seen many examples of working with text in the previous section. After all, it's not possible to print Hello Kotlin
without using a string, or at least it would be very awkward and inconvenient.
In this section, we'll discuss some of the more advanced features that allow you to manipulate text efficiently.
String interpolation
Let's assume now we would like to actually print the results from the previous section.
First, as you may have already noticed, in one of the previous examples, Kotlin provides a nifty println()
standard function that wraps the bulkier System.out.println
command from Java.
But, more importantly, as in many other modern languages, Kotlin supports string interpolation using the ${}
syntax. Let's take the example from before:
val hero = "Batman" println("Archenemy of $hero is ${archenemy(hero)}")
The preceding code would print as follows:
> Archenemy of Batman is Joker
Note that if you're interpolating a value of a function, you need to wrap it in curly braces. If it's a variable, curly braces could be omitted.
Multiline strings
Kotlin supports multiline strings, also known as raw strings. This feature exists in many modern languages, and was brought to Java 15 as text blocks.
The idea is quite simple. If we want to print a piece of text that spans multiple lines, let's say something from Alice's Adventures in Wonderland by Lewis Carroll, one way is to concatenate it:
println("Twinkle, Twinkle Little Bat\n" + "How I wonder what you're at!\n" + "Up above the world you fly,\n" + "Like a tea tray in the sky.\n" + "Twinkle, twinkle, little bat!\n" + "How I wonder what you're at!")
While this approach certainly works, it's quite cumbersome.
Instead, we could define the same string literal using triple quotes:
println("""Twinkle, Twinkle Little Bat How I wonder what you're at! Up above the world you fly, Like a tea tray in the sky. Twinkle, twinkle, little bat! How I wonder what you're at!""")
This is a much cleaner way to achieve the same goal. If you execute this example, you may be surprised that the poem is not indented correctly. The reason is that multiline strings preserve whitespace characters, such as tabs.
To print the results correctly, we need to add a trimIndent()
invocation:
println(""" Twinkle, Twinkle Little Bat How I wonder what you're at! """.trimIndent())
Multiline strings also have another benefit – there's no need to escape quotes in them. Let's look at the following example:
println("From \" Alice's Adventures in Wonderland\" ")
Notice how the quote characters that are part of the text had to be escaped using the backslash character.
Now, let's look at the same text using multiline syntax:
println(""" From " Alice's Adventures in Wonderland" """)
Note that there's no need for escape characters anymore.