How does string interpolation work in Kotlin?

meztihn picture meztihn · May 25, 2016 · Viewed 28k times · Source

Does the Kotlin compiler translate "Hello, $name!" using something like

java.lang.String.format("Hello, %s!", name)

or is there some other mechanism?

And if I have a class like this for example:

class Client {
  val firstName: String
  val lastName: String
  val fullName: String
    get() = "$firstName $lastName"
}

Will this getter return a cached string or will it try to build a new string? Should I use lazyOf delegate instead?

I know that there will be no performance issue unless there will be millions of calls to fullName, but I haven't found documentation about this feature except for how to use it.

Answer

yole picture yole · May 25, 2016

The Kotlin compiler translates this code to:

new StringBuilder().append("Hello, ").append(name).append("!").toString()

There is no caching performed: every time you evaluate an expression containing a string template, the resulting string will be built again.