Discover how to keep your code neat and your multiline text perfectly formatted without extra hassle!
Why Multiline strings with trimIndent in Kotlin? - Purpose & Use Cases
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.
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.
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.
""" Hello, This is a message. Regards """.replace(" ", "")
""" Hello, This is a message. Regards """.trimIndent()
You can write readable, well-indented code and still get perfectly formatted multiline text output automatically.
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.
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.