Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 3

Formatted Strings with Templates

Recommended resources

Hello! Welcome to the third lesson in our "Learn Kotlin Syntax" course.

In the last lesson, we covered the essentials of variable declaration with val and var, and saw how Kotlin's type inference makes your code more concise. You learned to prefer immutable vals and to declare types only when necessary.

Today, we'll build on that by exploring how Kotlin handles strings. The goal for this lesson is to utilize string templates and multiline strings to create formatted string values. As a Java developer, you're likely accustomed to string concatenation with + or using String.format(). You'll find Kotlin's approach to be more intuitive, readable, and powerful, especially for tasks common in backend development like generating logs, JSON, or SQL.

1. String Templates: The End of Tedious Concatenation

In Java, building a string from variables can be clumsy:

// Java
String name = "Alex";
int points = 100;
String message = "User " + name + " has " + points + " points.";

Kotlin simplifies this dramatically with string templates. You can embed variables and even entire expressions directly into a string literal.

Simple Variable Interpolation

For simple variables, you just prefix the variable name with a dollar sign ($).

To see this in action, let's start with a video that introduces the concept.

Kotlin String Templates: String Interpolation. Kotlin for Android #4.4

This video from Smartherd provides a clear, step-by-step introduction to string templates, comparing them to traditional concatenation.

Watch from the beginning to 02:06. Pay attention to how the $ syntax replaces the + operator for embedding variables.

As the video shows, the Java example above becomes much cleaner in Kotlin:

// Kotlin
val name = "Alex"
val points = 100
val message = "User $name has $points points."
println(message) // Output: User Alex has 100 points.

Interpolating Expressions

What if you need to do more than just insert a variable? For example, calling a method or performing a calculation. Kotlin handles this by wrapping the expression in curly braces ${...}.

Let's continue with the same video to see how to embed expressions.

Kotlin String Templates: String Interpolation. Kotlin for Android #4.4

This segment demonstrates how to use the ${...} syntax to embed complex expressions, object properties, and method calls within a string.

Watch from 02:06 to 07:01. Notice how any valid Kotlin code can be placed inside the curly braces, from simple arithmetic to accessing object properties.

This feature is incredibly useful. You can perform operations directly where they are needed, making the code's intent much clearer.

val s = "abc"
println("$s.length is ${s.length}") // Output: abc.length is 3

val a = 10
val b = 5
println("The sum of $a and $b is ${a + b}.") // Output: The sum of 10 and 5 is 15.

For an official definition and more examples, refer to the Kotlin documentation.

Strings | Kotlin Documentation

The official Kotlin documentation provides a concise reference for string templates.

Read the section titled 'String templates'. It reinforces what you've just seen and provides clear examples.


2. Multiline Strings: Preserving Your Formatting

Creating strings that span multiple lines in Java can be cumbersome, often involving a series of concatenated strings with \n characters. While Java 15 introduced text blocks ("""..."""), Kotlin has had a similar, powerful feature from the beginning.

Kotlin uses triple quotes (""") to create raw strings. These strings can contain newlines and any other characters without requiring escape sequences. This is perfect for embedding snippets of JSON, SQL, or HTML in your code.

Strings | Kotlin Documentation

This section of the documentation introduces multiline strings and the useful trimMargin() function.

Read the section 'Multiline strings' under the 'String literals' heading. Focus on the triple-quote syntax and the purpose of trimMargin().

Controlling Indentation

When you embed a multiline string in your code, the indentation of your code can add unwanted whitespace to the string. Kotlin provides two handy functions to manage this:

  1. trimMargin(): Removes leading whitespace up to a specified margin prefix (by default, |). This is useful for aligning the text block visually.
  2. trimIndent(): Removes the minimum common indentation from all lines, which is often more convenient as you don't need to add a special character to each line.

The following image clearly illustrates the effect of trimIndent().

This image shows two functions. `indentedStringLiteral()` returns a raw multiline string with its leading whitespace preserved. `unindentedStringLiteral()` uses `trimIndent()` to remove that common leading whitespace, resulting in a clean, unindented string.

Here's a practical example using trimIndent():

fun getJsonPayload(user: String, id: Int): String {
    return """
        {
            "user": "$user",
            "id": $id,
            "status": "active"
        }
    """.trimIndent()
}

println(getJsonPayload("Maria", 42))

This will print a perfectly formatted JSON string, without the leading indentation from the source code.

The Dollar Sign Dilemma in Raw Strings

There's one catch: since raw strings use $ for templating, how do you include a literal dollar sign, for example in a MongoDB query or when representing currency?

You can't use $ because raw strings don't support escape sequences. The recommended solution is to use an expression template to insert the dollar character itself: ${'$'}.

This article from Baeldung provides an excellent, practical example related to your backend experience.

Kotlin String Templates

This article from Baeldung explains how to handle literal dollar signs in multiline strings, using a MongoDB query as a relevant example.

Read section 5, 'Using Dollar Sign in Multiline String'. The scenario with the MongoDB query ($gte) is a perfect illustration of this common problem and its elegant solution in Kotlin.


3. Hands-On Practice

Now, let's combine these concepts. Open your App.kt file in IntelliJ IDEA and replace the main function with the following exercise.

Goal: Create a function that generates a formatted SQL INSERT statement using a multiline string and string templates.

  1. Define two vals: tableName with the value "users" and userName with the value "guest".
  2. Define a var named loginCount and initialize it to 1.
  3. Create a function named generateInsertQuery that takes the table name, user name, and login count as parameters and returns a String.
  4. Inside the function, use a multiline string to construct an SQL INSERT statement. Use string templates to embed the parameters.
  5. Use trimIndent() to ensure the resulting SQL string has no extra leading whitespace.
  6. In your main function, call generateInsertQuery with your variables and print the result.
  7. Increment loginCount in main and call the function again to see the updated query.
Click to see a possible solution
fun generateInsertQuery(table: String, user: String, logins: Int): String {
    return """
        INSERT INTO $table (username, login_count, last_login)
        VALUES ('$user', $logins, NOW());
    """.trimIndent()
}

fun main() {
    val tableName = "users"
    val userName = "guest"
    var loginCount = 1

    // First call
    val query1 = generateInsertQuery(tableName, userName, loginCount)
    println("--- First Query ---")
    println(query1)

    // Increment and call again
    loginCount++
    val query2 = generateInsertQuery(tableName, userName, loginCount)
    println("--- Second Query ---")
    println(query2)
}

Conclusion

In this lesson, you've mastered two of Kotlin's most convenient features for working with text. You can now create clean, readable, and dynamic strings with ease.

Key Takeaways:

  • String Templates replace Java's string concatenation. Use $ for simple variables and ${...} for expressions.
  • Multiline Strings, created with """...""", allow you to write strings that span multiple lines without messy escaping.
  • Indentation Control with trimIndent() and trimMargin() keeps your multiline strings clean.
  • To include a literal $ in a raw string, use the ${'$'} syntax.

Next Lesson Preview:

Now that you can declare variables and format strings, the next logical step is to perform repetitive tasks. In our next lesson, we will explore how to write a for loop to iterate over ranges, progressions, and collections, which will open up a new level of dynamic programming capabilities.