0
0
Kotlinprogramming~5 mins

Multiline strings with trimIndent in Kotlin

Choose your learning style9 modes available
Introduction

Multiline strings let you write text that spans many lines easily. Using trimIndent() removes extra spaces from the start of each line, making the text neat.

When you want to write a message or paragraph that spans multiple lines in your code.
When you need to include formatted text like JSON or XML inside your Kotlin code.
When you want to keep your code readable without extra spaces messing up the text layout.
Syntax
Kotlin
"""
    Your multiline text here
    on multiple lines
""".trimIndent()

Use triple quotes """ to start and end multiline strings.

trimIndent() removes common leading spaces from all lines.

Examples
This creates a string with two lines: "Hello," and "Kotlin!" without extra spaces at the start.
Kotlin
"""
    Hello,
    Kotlin!
""".trimIndent()
All lines have the same indentation removed, so the string is neat.
Kotlin
"""
        Line one
        Line two
        Line three
""".trimIndent()
Without trimIndent(), the spaces before each line stay in the string.
Kotlin
"""
    This line has no extra spaces
    This line too
"""
Sample Program

This program prints a neat multiline message without extra spaces at the start of each line.

Kotlin
fun main() {
    val message = """
        Dear User,
        Welcome to Kotlin programming!
        Enjoy learning.
    """.trimIndent()
    println(message)
}
OutputSuccess
Important Notes

trimIndent() only removes the smallest common indent from all lines.

If lines have different indents, only the smallest one is removed.

You can also use trimMargin() if you want to remove indentation marked by a special character.

Summary

Multiline strings use triple quotes to hold text on many lines.

trimIndent() cleans up leading spaces for neat output.

This helps keep code readable and output formatted nicely.