3 minutes read

Sometimes, you need to put the values of variables in a text. Luckily for you, Kotlin can help you with that using string templates. In this topic, we will discuss their purpose.

Suppose we need to display a message about today's temperature in Celsius:

The temperature in ... is ... degrees Celsius.

Instead of ... we need to display certain values.

If we have two variables city and temp, we can build the resulting string with concatenations:

val city = "Paris"
val temp = "24"

println("The temperature in " + city + " is " + temp + " degrees Celsius.")

It is a simple solution. But is it perfect? No. It's rather awkward.

Kotlin provides a more convenient way to do the same thing using string templates. How do they work? To add a variable value to a string, write the dollar sign $ before a variable name:

val city = "Paris"
val temp = "24"

println("The temperature in $city is $temp degrees Celsius.")

The code becomes more readable. Both code snippets print the same message:

The temperature in Paris is 24 degrees Celsius.

If we do not want to print a string, we can create a variable:

val value = "55"
val currency = "dollars"
val price = "$value $currency" // "55 dollars"

We recommend using string templates to build strings with variable values. Try using it instead of string concatenation.

Templates for expressions

You can use string templates to put the result of an arbitrary expression in a string. To do that, include the entire expression in curly braces {...} after the dollar sign $. For example:

val language = "Kotlin"
println("$language has ${language.length} letters in the name")

It prints:

Kotlin has 6 letters in the name

Here {language.length} is an expression that will be evaluated. If you skip the braces, it will output something different:

Kotlin has Kotlin.length letters in the name

So, always use curly braces for expressions in string templates to avoid these mistakes. Do not add them if you want to output only a variable value even though it does work.

Idiom

Idioms are templates for clear and readable code. These patterns clarify the code for other people, so it is a good idea to use them. All idioms are endorsed by the community, so using them will bring you closer to the genuine Kotlin-style code. You can find an exhaustive list of idioms at Kotlin docs.

The idiom we'll look at is the string interpolation:

val language = "Kotlin"
println("Have a nice $language!")        // nice code
println("Have a nice " + language + "!") // bad practice

Conclusion

What do you need to remember from this topic? There are two main points:

  1. Use string templates to insert variable values into a string: "this string has $value".

  2. If you would like to get an arbitrary expression, use curly braces: "The length is ${str.length}".

1594 learners liked this piece of theory. 10 didn't like it. What about you?
Report a typo