What are string templates in Kotlin?
Overview
String templates are $. If it's a complex expression, it has to be enclosed within ${}. Since string literals cannot be modified after creation, using string templates gives us a simpler way to add expressions in strings without creating multiple strings.
Example
As an example, consider there are two variables, x and y. We need to create a string that includes their values and the value of their sum. How Kotlin makes this simpler as compared to Java is shown below:
Java code
class SumInString {public static void main( String args[] ) {int x = 3;int y = 4;int sum = x + y;String sumString = "The sum of " + x + " and " + y + " is " + sum + ".";System.out.println( sumString );}}
Kotlin code
fun main(args : Array<String>) {val x = 3val y = 4val sumString = "The sum of $x and $y is ${x + y}."println(sumString)}
Notice how the Kotlin code is much simpler and cleaner, and even the summation part is embedded in the expression.
Embedded logic
String templates can contain logic. They can even be nested inside other string templates. The following lines of code show how logic can be implemented within a string template.
fun main(args : Array<String>) {val n = 3val signString = "$n is ${if(n >= 0) "positive" else "negative"}"println(signString)}
The $ keyword as part of the string
Anything immediately following the $ keyword will always be evaluated as an expression inside a string template, but if we want $ to be a part of the actual string, we need to escape it using \.
fun main() {val escapedString = "This \$dollar and $ will actually be visible"println(escapedString)}
Free Resources