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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With