Skip to Content
Course content

88: String Templates and Raw Strings

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of string templates like a professional email template you might use at work. Instead of rewriting the entire email every time you contact a new client, you have a master version with placeholders like [Client Name] or [Project Deadline]. When it's time to send, you just swap those brackets for the actual data. It saves you from the tedious work of cutting and pasting fragments of text together.

In Kotlin, we do this exact same thing. Instead of using the + operator to glue strings together—which, let's be honest, becomes a nightmare once you have more than two variables—we embed the variables directly into the string using the $ symbol.

Stop Glueing Your Strings Together

If you're coming from Java, you're probably used to concatenating strings with a lot of quotation marks and plus signs. In Kotlin, that's mostly a thing of the past. If you just need to drop a variable into a sentence, you use the dollar sign.

val playerName = "Kaelthas"
val score = 1250
println("Player $playerName has reached a score of $score!") 
// Output: Player Kaelthas has reached a score of 1250!

But what happens when you need to do something more complex? Maybe you want to perform a calculation or call a function right inside that string. That's where curly braces come in. Anything inside ${} is treated as actual Kotlin code, evaluated, and then converted to a string.

val itemsInCart = 3
val pricePerItem = 19.99
println("Your total is: $${itemsInCart * pricePerItem}") 
// Output: Your total is: $59.97

I've noticed a few people get tripped up when they want to print a literal dollar sign. If you need a $ to actually appear in your text without Kotlin thinking it's a template, just escape it with a backslash: \$.

Handling the Messy Stuff with Raw Strings

Now, standard strings are great for single lines, but they fall apart when you're dealing with multi-line text, like a JSON response, an SQL query, or a long block of HTML. Using \n for every new line is visually cluttered and makes the code hard to read.

Enter "Raw Strings." By wrapping your text in triple quotes ("""), you tell Kotlin: "Everything in here is literal. Don't worry about escape characters, and just keep the line breaks exactly as I've typed them."

val jsonResponse = """
{
  "user": "Dev_Guru",
  "status": "Active",
  "permissions": ["read", "write"]
}
"""

It's much cleaner, right? You can see the structure of the JSON immediately without hunting through \n and \" symbols.

Taming the Indentation

There is one annoying side effect to raw strings. Because they capture everything, they also capture the whitespace you use to indent your code. If your raw string is inside a function or a class, those leading tabs or spaces become part of the string itself, which usually isn't what you want when you actually print the output.

To fix this, Kotlin provides .trimIndent(). This function looks at the common minimal indentation of all the lines and removes it. I almost always use this with raw strings to keep my code aligned without ruining my output formatting.

fun printWelcomeMessage() {
    val message = """
        Welcome to the System!
        Please ensure you have:
        - Updated your password
        - Accepted the TOS
    """.trimIndent()
    
    println(message)
}

If you have a specific margin you want to strip away (perhaps you're using a pipe character | to mark the start of your text), you can use .trimMargin() instead. It's a bit more surgical and gives you total control over where the "real" text begins.




📋 Practical Task

Build a Dynamic System Status Report

Your task is to create a program that generates a formatted system report. You'll need to combine string templates for the data and a raw string for the layout.

Requirements:

  • Create three variables: serverName (String), uptimeDays (Int), and cpuLoad (Double).
  • Create a multi-line raw string that acts as a report template. It should look like this:
    --- SYSTEM REPORT ---
    Server: [serverName]
    Uptime: [uptimeDays] days
    Load: [cpuLoad]%
    --------------------
  • Use string templates to inject your variables into that raw string.
  • Apply .trimIndent() to the raw string so there is no leading whitespace in the final output.
  • Print the final report to the console.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.