Strings and Interpolation in Kotlin

Strings represent sequences of characters and are used to store text in Kotlin programs. Kotlin provides versatile features to work with strings, including templates, interpolation, concatenation, and multiline string support, making text handling both concise and expressive.

1. Creating Strings

Kotlin supports two main ways to declare string literals:

2. Concatenating Strings

You can combine multiple strings using the + operator:

val firstName = "John"
val lastName = "Doe"
val fullName = firstName + " " + lastName
println(fullName) // Output: John Doe

3. String Templates and Interpolation

Kotlin allows embedding variables and expressions directly into strings using templates:

4. Calling Functions Inside Templates

You can invoke functions directly within string templates for dynamic output:

fun greet(name: String) = "Hello, $name!"
val message = greet("Kotlin")
println("Message: $message") // Output: Message: Hello, Kotlin!

5. Common String Operations

Kotlin provides multiple built-in methods for manipulating strings:

val text = "  Kotlin is fun!  "
println(text.length)         // Output: 18
println(text.trim())         // Output: Kotlin is fun!
println(text.uppercase())    // Output:   KOTLIN IS FUN!  
println(text.substring(2, 8)) // Output: Kotlin
println(text.replace("fun", "awesome")) // Output:   Kotlin is awesome!  

6. Multiline Strings and Margins

Raw strings can include leading margins, which can be removed using trimMargin():

val poem = """
    |Roses are red,
    |Violets are blue,
    |Kotlin is fun,
    |And so are you.
  """.trimMargin()
println(poem)
/* Output:
Roses are red,
Violets are blue,
Kotlin is fun,
And so are you.
*/

7. Advantages of Using String Templates

8. Example Program

fun main() {
    val firstName = "Emma"
    val lastName = "Stone"
    val age = 30

    val greeting = "Hello, $firstName $lastName! You are $age years old."
    println(greeting)

    val poem = """
      |Roses are red,
      |Violets are blue,
      |Kotlin is fun,
      |And so are you.
    """.trimMargin()
    println(poem)
}

Output:

Hello, Emma Stone! You are 30 years old.
Roses are red,
Violets are blue,
Kotlin is fun,
And so are you.