Today we will check a feature kotlin has which is called as String Template.

Using String Template.

Now let’s do something that we typically do in Java and that is overriding the string method because if we run the code.
val student1= Student ("Besho",500)
student1.name = "Ali"
println(student1)

and to make sure you get it, the student class is

class Student (var name : String , val id : Int) 
{

}

we’ll see that the output will be just the instance reference and that’s usually not what we want when we were printing the student, we want a nice string telling us the contents of the instance.

so we will have IntelliJ generate the (to string) overwrite for us by right-clicking, then going to (generate) and then going to select (to string) and I want to include both property values in the string

The code that will be generated for us inside the Student class is:

class Student (var name : String , val id : Int) 
{
         override fun toString(): String {
            return "Student(name='$name' , id= $id)"
         }
}
and you’ll notice that it’s using these dollar values in here ($name, $id).
the output will be
Student(name=Ali , id= 500)
so essentially what’s happening with these dollar signs is that the value of the variable is being substituted into the string and that’s really convenient, you know it’s much better than having to use string concatenation or even the boring ‘format.’ method.

 Escaping String Template.

let’s take a look at using the dollar sign within a string template in a bit more detail.
so let’s say we have a val called price and I have to print the word $price in my string, then I have to escape the $ by using /
val price = 4.22
//We want to print the word price with the dollar sign $price
println("The $price will be replaced by 4.22,  but \$price will be print what we want")

another great feature, when you’re going to substitute the value of an expression you have to start with a dollar sign and then you have to enclose the value of the expression between curly braces so that’s what we’re doing

    val x= 10.99
    val y= 20
    println("The value of $x divided by $y is ${x/y}")

the output should be something like this.

[code]The value of 10.99 divided by 20 is 0.5495 [/code]

You can do something like [code]println(“The var1 is referentially equal to var2 : ${var1===var2}”)[/code], which will return true or false 😀

Last note!

When you reference a property value from outside the class that’s considered to be an expression so if we want it to do something like this

  println("The student's id is $student.id")

it won’t work, instead, we have to do it like this.

  println("The student's id is ${student1.id}")

so that’s it for string templates :), it’s a really cool feature in  Kotlin that I think you’re going to use a lot because we often concatenate string values together or using string .format,  and you no longer have to do that you can just substitute the values thanks to Kotlin !.