Using String Template.
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)" } }
Escaping String Template.
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 !.