String Templates and Multiline Strings in Kotlin

Reading Time: 3 minutes

String Templates

In programs, we often create strings with embedded values of expressions. Concatenating values to create strings using the + operator makes the code verbose and hard to maintain. String templates solve that problem by providing an elegant solution.

Within a double-quoted string, the $ symbol can prefix any variable to turn that into an expression. If the expression is more complex than a simple variable, then wrap the expression with ${}.

Here’s an example with a string template. Also, it contains a plain string with embedded $ symbols that are used as literal.

val price = 11.03
val taxRate = 1.12
val output = "The amount $price after tax comes to $${price * (1 + taxRate)}"
val disclaimer = "The amount is in US$, that's right in \$only"
println(output)
println(disclaimer)

In the string template assigned to output, the first $ symbol is used as a delimiter for the expression, the variable name, that follows it. The second $ symbol is literal since it’s followed by another $, which isn’t a variable or expression. The third $ symbol prefixes an expression that’s wrapped in {}. The other $ symbols in the code are used as literals. Let’s take a peek at the output of the code:

The amount 11.03 after tax comes to $23.3836

The amount is in US$, that’s right in $only

Let’s take the code with var we saw previously and modify it slightly to use a string template.

var factor = 4
fun doubleIt(n: Int) = n * factor
var message = "The factor is $factor"
factor = 0
println(doubleIt(2))
println(message)

Once again, don’t run the code, but eyeball it and figure out the output of this code. Does it correspond with the following output?

0

The factor is 4

The variable factor within the function doubleIt() binds to the variable outside its immediate scope—that is, in its lexical scope. The value of the factor at the time of the function call is used. The string template, on the other hand, is evaluated when the variable message is created, not when its value is printed out. These kinds of differences increase cognitive load and make the code hard to maintain and also error-prone. No need to torture fellow programmers with code like this. It’s inhumane. Again, as much as possible prefer val over var.

Multiline Strings

The infamous + operator is often used to create multiple lines of strings, and that leads to nasty code that’s hard to maintain. Kotlin removes that ceremony with a multiline string, which is a raw string that contains line breaks. Multiline strings can also act as string templates.

Let’s create a string that runs across several lines, but without the + operator.

val name = "Uzair"
val memo = """Dear $name, a quick reminder about the
party we have scheduled next Tuesday at
the 'Low Ceremony Cafe' at Noon. | Please plan to..."""
println(memo)

The multiline string starts with three double quotes, contains the string template expression to evaluate the variable name, and ends with three double quotes.

The output of this code is multiple lines of string with the embedded expression evaluated.

Dear Uzair, a quick reminder about the

party we have scheduled next Tuesday at

the ‘Low Ceremony Cafe’ at Noon. | Please plan to…

Multiline Strings within a function

let’s take an example.

fun createMemoFor(name: String): String {
if (name == "Uzair") {
val memo = """Dear $name, a quick reminder about the
party we have scheduled next Tuesday at
the 'Low Ceremony Cafe' at Noon. | Please plan to..."""
return memo
}
return ""
}
println(createMemoFor("Uzair"))

Here’s the output that shows the fix worked.

Dear Uzair, a quick reminder about the

party we have scheduled next Tuesday at

the ‘Low Ceremony Cafe’ at Noon. | Please plan to…

For more information on Kotlin visit: https://www.w3schools.com/kotlin/index.php

Checkout more Kotlin Blogs here.

Written by 

Mohd Uzair is a Software intern at Knoldus. He is passionate about java programming. He is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. He is a quick learner & curious to learn new technologies. His hobbies include watching movies, surfing youtube, playing video games.