How does string interpolation work in Kotlin?

Solution 1:

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.

Solution 2:

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.

Solution 3:

As you know, in string interpolation, string literals containing placeholders are evaluated, yielding a result in which placeholders are replaced with their corresponding values. so interpolation (in KOTLIN) goes this way:

var age = 21

println("My Age Is: $age")

Remember: "$" sign is used for interpolation.

Solution 4:

Always use curly brackets to avoid surprises. For example if you're string interpolating an object property, you should be enclosing it in curly brackets:

print("Your username is ${user.username}\n")