Cookie Preferences

We use cookies to enhance your experience. Choose your preference for cookie usage.

Essential cookies are required for basic functionality. Additional cookies help us improve our service and provide analytics.

View third-party services
  • Google Analytics: Website traffic analysis and conversion tracking
  • RudderStack: Analysis of user interactions with the website
  • Microsoft Clarity: User behavior analysis & session recordings
  • Facebook Pixel: Marketing analysis of user activity
KotlinStrings, arrays and ranges

String templates

Sometimes you will meet a situation when you need to put the values of variables in a text. Kotlin allows you to do that using string templates. In this lesson, we will consider what is it and why it is better than other ways.

Templates for variables

Suppose we need to display an information about a temperature (in Celsius) in a city.

Now, the temperature in ... is ... degrees Celsius.

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

If we have two variables city and temperature, we can build the result string using a sequence of concatenations:

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

println("Now, the temperature in " + city + " is " + temp + " degrees Celsius.")

Of course, this code is simple enough and works correctly. But it is not very concise.

Kotlin provides a more convenient way to do the same using string templates. To put a value of a variable to a string, use the dollar sign $ before the variable's name.

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

println("Now, the temperature in $city is $temp degrees Celsius.")

This code is more readable than the same fragment with concatenations.

You may check, that both considered code snippets print the same:

Now, the temperature in Paris is 24 degrees Celsius.

If we do not want to print a string, we can create a variable and use it as we need in further:

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

String templates is a recommended way to build strings based on values of variables. Always prefer it.

Templates for expressions

String templates can be used to put a result of an arbitrary expression in a string. To do that, include the entire expression in curly braces {...} after the dollar sign $. Here is an 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 to be evaluated. If you skip the braces, it will output something else:

Kotlin has Kotlin.length letters in the name
So, always use curly braces for expressions in string templates to avoid such mistakes. But do not add them if you want to output only a value of a variable even though it works.
How did you like the theory?
Report a typo