I am learning Kotlin and I came across string template, and find it very amazing! Soon I discovered that a number can be converted to string with the help of it.
I know that toString()
is the recommended way. But I want to understand, is the below method advisable to use and what good is the efficiency?
fun main() {
val integer: Int = 19
val string1: String = "$integer"
val string2: String = integer.toString()
println(string1)
println(string2)
}
Output:
19
19
Check This SO thread to understand how string interpolation is actually implemented in kotlin:
Bottom line you'll have a StringBuilder
that is created every time when you perform an interpolation. This alone makes this method less efficient then a "simple and straight-to-the-point" integer.toString()
An additional reason is code clarity I would say: the usage of string interpolation for conversion from integer to string looks non-intuitive - so use the right tool for the right job, you know :)