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
{...}
after the dollar sign $
. Here is an example:val language = "Kotlin"
println("$language has ${language.length} letters in the name")
Kotlin has 6 letters in the name
{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.