Kotlin String template : Explanation with Examples

Introduction :

String is a sequence of characters. All strings are of String class. For example, “Hello World” is a string. One more important thing is that String is immutable in Kotlin, i.e. you cann’t change any character of a string variable. Kotlin has introduced one new concept for string called string template. It allows us to include one variable or expression to a string. In this tutorial, we will show you how string template works in kotlin with different examples :

String template with variables :

String template works with variables and complex expressions. If you place any variable with a ”$” sign in front of it, it will be treated as a string template in kotlin. For example :

fun main(args: Array) {
    val rank = 5

    println("Rank for Albert is : $rank")
}

It will print the below output :

Rank for Albert is : 5

As you can see that the value of rank is concatenated to the string literal when we have added ’$’ before that variable.

kotlin string template

String template with expression :

String template can be used with a simple or complex expression. e.g. :

fun main(args: Array) {
    val currentValue = 5

    println("Increment by one : ${currentValue+1}")
}

It will print :

Increment by one : 6

As you can see everything inside a curly braces is an expression. This expression is evaluated and concatenate with the string. We can even use a more complex expression like below :

fun main(args: Array) {
    val currentValue = 50

    var result = "$currentValue is ${if(currentValue % 2 == 0) 
    "even" else 
    "odd"}"

    println(result)
}

Output :

50 is even

kotlin string template

With raw string :

Raw strings is delimeted by triple quoted that supports special characters without using a "". Since they doesn’t support any escape character, the below string will not add any newline to it :

fun main(args: Array) {
    var result = """Hello \n World"""

    println(result)
}

It will simply print :

Hello \n World

We can get help of string template to use escaped characters in raw string like :

fun main(args: Array) {
    var result = """Hello ${"\n"} World"""

    println(result)
}

It will add one newline character between the two words. kotlin string template Similarly, we can add other string template in raw strings.

Conclusion :

String template removes the requirement of ”+” while concatenating string and other variable or expressions. It is really one of the best feature that kotlin provides. Go through the examples we have discussed above and drop a comment below if you have any queries.

You might also like :