Kotlin string interpolation gotchas
Kotlin’s string interpolation is an amazing feature. Combined with autocompletion support by the Intellij IDE, writing interpolated strings is as easy as writing string literals.
When experimenting with strings, I found some pretty interesting cases worth sharing. These cases highlight how different ways of using interpolation result in new strings being created vs same strings being used from the JVM string constant pool.
Case 1: String literals
Here we interpolate a string literal and compare it with a non interpolated string. On decompiling, we can see that creating strings via interpolation and concatenation result in the exact same bytecode.
Case 2: Array interpolation
When an array is interpolated, the Kotlin compiler generates a StringBuilder resulting in different string literals.
Case 3: String concatenation
As expected, string concatenation behaves the same way as case 1.
Case 4: Function interpolation
Here we interpolate the result of the
concat function invocation. The function call results in s7 and s8 pointing to two different string instances.
Hope you’ve found this interesting. Let me know if you have something to share on this.
Thanks to Severin Rudie for proof reading this article.
Happy coding :)