Kotlin Fundamental

String Templates in Kotlin

Pinterest LinkedIn Tumblr

In this post, we’ll learn about string templates and in other words what is String Interpolation. in Kotlin we have a special type of concept String Interpolation. In this article, we’ll discuss in detail with example.

Let us start with some example, I’m going to define one variable and appends it with title val

        val website = "Android"
        val title = website + "Developer Blog"

Let print the title value, the output is as expected

Output -  AndroidDeveloper Blog

In Kotlin, we have a concept of String Interpolation, so no longer to use the + keyword or the String concatenation. Now, what is the String Interpolation? let change above statement with String Interpolation.

        // define some variables
        val website = "Android"
        val title = "$website Developer Blog"

Here we removed + sign and used $ keyword followed by the name. So Java compiler what it will do, It will simply evaluate name and then print it with other string.

The output will be the same, so let’s run the code here the output we get Android Developer Blog as expected.

So let’s take some more example, create an android project
        // define some variables
        val title = "Android"
        val name = "$title Developer Blog"

        textView.text = "The full statement is $name"
Now I want to add a number of characters in name value.
        // define some variables
        val title = "Android"
        val name = "$title Developer Blog"

        textView.text = "The full name is $name The length of name is ${name.length}"
Let’s take some numeric value example
        val a = 22
        val b = 23
        textView.text = "The sum of $a & $b => ${a + b}"
Output is - The sum of 22 & 23 => 45
Deal with class
   {     // create a object on rect
        val rect = Rect()
        print("The Rect width is ${rect.width} and height is ${rect.height} ")

    class Rect {
        var width = 12
        var height = 14

In this post, we learned string templates and concepts String Interpolation. This is the beauty of Kotlin, In the one statement, you can manage everything. That why we say Kotlin is more powerful then java and it is more expressive and concise.

Why we used Kotlin for Android Development

Write A Comment