Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does string interpolation work in Kotlin?

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.

like image 935
meztihn Avatar asked May 25 '16 15:05

meztihn


People also ask

How do you use string interpolation in Kotlin?

String interpolation is variable substitution with its value inside a string. In Kotlin, we use the $ character to interpolate a variable and ${} to interpolate an expression. Kotlin string formatting is more powerful than basic interpolation.

What is string templating Kotlin?

String templates allow you to include variable references and expressions into strings. When the value of a string is requested (for example, by println ), all references and expressions are substituted with actual values.

How does interpolation work in programming?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.


2 Answers

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.

like image 174
yole Avatar answered Oct 21 '22 09:10

yole


Regarding your 2nd question: If you need caching for fullName, you may and should do it explicitly:

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

This code is equivalent to your snipped except that the underlying getter getFullName() now uses a final private field with the result of concatenation.

like image 45
voddan Avatar answered Oct 21 '22 10:10

voddan