Interpolating a string

Kotlin:
Interpolating a string

How to:

fun main() {
    val name = "Alex"
    val age = 29
    // Interpolate variables into the string
    val greeting = "Hello, my name is $name and I am $age years old."
    println(greeting) // Output: Hello, my name is Alex and I am 29 years old.

    // Expressions within strings
    val announcement = "Next year, I'll be ${age + 1}!"
    println(announcement) // Output: Next year, I'll be 30!
}

Deep Dive

Kotlin, influenced by other modern languages, introduced string interpolation as a cleaner alternative to Java’s string concatenation. It improves readability and simplifies code.

Historically, Java required verbose concatenation using +, which could be both hard to read and less efficient, as it created multiple string objects. Kotlin’s approach is more powerful, allowing not just variable embedding but also expression evaluation within strings.

Under the hood, Kotlin compiles this interpolation into StringBuilder operations or string concatenation, depending on the complexity, taking the burden off the developer.

Alternatives to string interpolation include template engines for extensive text manipulation, but in code, interpolation is generally the quickest way to include dynamic content.

See Also