String interpolation
Kotlin allows access to variables (and other expressions) directly from within string literals, usually eliminating the need for string concatenation.
Consider the following Java code:
String name = "Alex";
String greeting = "Hello " + name + "!";
which becomes this in Kotlin:
val name = "Alex"
val greeting = "Hello $name!"
$name
is replaced by the contents of the variable name
, more precisely by a call to its toString()
method.
The general syntax is $variable
.
Please note in the example that the final !
is automatically interpreted as not belonging to the variable name.
This is because the Kotlin compiler interprets everything after the introductory $
as a reference name until it encounters a character that is not part of a common identifier.
To resolve all the ambiguities, or to use more complex expressions, there is the alternative syntax ${expression}
, which is to enclose the expression in curly braces.
Thus, the following is also possible:
val person = Person(firstName = "Alex", lastName = "Example")
val greeting = "Hello ${person.firstName}!"