0
0
Kotlinprogramming~3 mins

Why Multiline strings with trimIndent in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to keep your code neat and your multiline text perfectly formatted without extra hassle!

The Scenario

Imagine writing a long message or a block of text inside your code, like a poem or an email template. You try to keep it neat by indenting it to match your code style, but when you run the program, the extra spaces mess up the formatting.

The Problem

Manually removing spaces from each line is slow and tiring. You might miss some spaces or add too many, making the text look ugly or broken. This wastes time and causes frustration, especially when the text is long or changes often.

The Solution

Using multiline strings with trimIndent() lets you write the text naturally with indentation for your code style. When the program runs, it automatically removes the common leading spaces, so the text looks clean and perfect without extra work.

Before vs After
Before
"""
    Hello,
    This is a message.
    Regards
""".replace("    ", "")
After
"""
    Hello,
    This is a message.
    Regards
""".trimIndent()
What It Enables

You can write readable, well-indented code and still get perfectly formatted multiline text output automatically.

Real Life Example

When creating an email template or a SQL query inside your Kotlin code, trimIndent() helps keep your code clean and your text formatted nicely without extra manual editing.

Key Takeaways

Writing multiline text inside code can get messy with indentation.

Manually fixing spaces is slow and error-prone.

trimIndent() cleans up indentation automatically for neat output.