androidengineers.Book a session

Kotlin Basics and Syntax

String Templates and Operations

article15 minEasy

Build text without obscuring the calculation

String templates insert a value using $name, or evaluate an expression inside ${...}. Strings are immutable; operations such as trim return a new string rather than modifying the original.

fun main() {
    val raw = "  Compose  "
    val label = raw.trim()
    val count = 4
    println("$label has ${label.length} characters")
    println("Next lesson: ${count + 1}")
    println("Price marker: ${'$'}")
}

The first output reports seven characters. The raw input still includes its surrounding spaces. Use triple-quoted strings with trimIndent() for readable multiline text. Interpolation still occurs inside triple quotes; they are not a way to disable templates.

Avoid interpolating secrets into logs. Also keep expensive transformations out of repeated UI rendering when their inputs have not changed. On JVM, string length counts UTF-16 code units, so it is not a reliable count of user-perceived characters such as emoji.

Exercise

Format a course receipt with a title, quantity, and total in three lines. Keep the numeric calculation in a separate variable. Test a title with leading spaces and one containing an emoji.

Check: the displayed title should be trimmed, and your code should not assume that length measures visible symbols.

Reference: Strings

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
String Templates and Operations | Kotlin Core Programming | Android Engineers