String Templates

Inserting Values with $

Example

Put $name inside a string to insert a variable, or ${expression} for anything more complex.

fun main() {
    val user = "Priya"
    val items = 3
    val price = 150

    println("Hi $user!")
    println("You have $items items")
    println("Total: ${items * price}")
    println("Name has ${user.length} letters")
    println("Status: ${if (items > 0) "ready to checkout" else "empty cart"}")
}

Output

Hi Priya!
You have 3 items
Total: 450
Name has 5 letters
Status: ready to checkout

When Braces are Needed

Example

$ takes the longest valid name after it. Use braces when the name is followed by letters, or when you access a property.

fun main() {
    val qty = 5
    val name = "Amit"
    println("${qty}kg")             // without braces: $qtykg -> error
    println("${name.uppercase()}")
    println("$name.uppercase()")    // only $name is replaced!
}

Output

5kg
AMIT
Amit.uppercase()

Templates vs Java

// Java
String msg = "Hi " + user + ", total is " + (items * price);
String msg2 = String.format("Hi %s, total is %d", user, items * price);
// Kotlin
val msg = "Hi $user, total is ${items * price}"

Example

For decimal formatting, Kotlin still has format:

fun main() {
    val amount = 1234.5
    println("Amount: ${"%.2f".format(amount)}")
    println("Percent: ${"%.1f".format(87.456)}%")
}

Output

Amount: 1234.50
Percent: 87.5%