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.

An interpolated cat

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.

String literal interpolation
Decompiled bytecode showing s1 and s2 are the same string literal

Case 2: Array interpolation

When an array is interpolated, the Kotlin compiler generates a StringBuilder resulting in different string literals.

Array object interpolation
Decompiled bytecode shows new StringBuilder instances created

Case 3: String concatenation

As expected, string concatenation behaves the same way as case 1.

String concatenation interpolation
Bytecode decompiled to Java

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.

Function interpolation
Bytecode decompiled to Java

Closing words

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 :)