0
0
Kotlinprogramming~15 mins

Multiline strings with trimIndent in Kotlin - Deep Dive

Choose your learning style9 modes available
Overview - Multiline strings with trimIndent
What is it?
Multiline strings in Kotlin let you write text that spans several lines without needing special characters for new lines. The trimIndent function removes common leading spaces from each line, making the string look neat and aligned in your code. This helps keep your code readable while preserving the intended text format.
Why it matters
Without trimIndent, multiline strings often include unwanted spaces from code indentation, making the output messy or incorrect. This can cause problems when formatting text, generating code, or working with data like JSON or XML. trimIndent solves this by cleaning up indentation automatically, saving time and avoiding bugs.
Where it fits
Before learning this, you should know basic Kotlin strings and how to write simple multiline strings. After this, you can explore other string manipulation functions like trimMargin or raw strings, and how to use strings in templates and formatting.
Mental Model
Core Idea
trimIndent cleans up the shared leading spaces in multiline strings so the text looks exactly as intended without extra indentation.
Think of it like...
Imagine writing a letter on lined paper but holding the paper crooked. trimIndent straightens the paper so all lines start evenly, making the letter easy to read.
Multiline string example:
┌─────────────────────────────┐
│     """                   │
│         Hello,             │
│         Kotlin!            │
│     """.trimIndent()      │
└─────────────────────────────┘

After trimIndent removes leading spaces:
"Hello,\nKotlin!"
Build-Up - 7 Steps
1
FoundationBasic multiline strings in Kotlin
🤔
Concept: How to write strings that span multiple lines using triple quotes.
In Kotlin, you can write a string across several lines by enclosing it in triple quotes """. For example: val text = """ Hello, Kotlin! """ This string includes the line breaks exactly as typed.
Result
The string contains the text with line breaks: Hello, Kotlin!
Knowing how to write multiline strings lets you include formatted text easily without special characters for new lines.
2
FoundationIndentation problem in multiline strings
🤔
Concept: Understanding how code indentation affects multiline strings.
If you indent the multiline string in your code for readability, those spaces become part of the string: val text = """ Hello, Kotlin! """ This string includes the spaces before 'Hello' and 'Kotlin!'.
Result
The string contains unwanted spaces: Hello, Kotlin!
Indentation in code can unintentionally add spaces to strings, causing formatting issues.
3
IntermediateUsing trimIndent to fix indentation
🤔Before reading on: do you think trimIndent removes all spaces or only the shared leading spaces? Commit to your answer.
Concept: trimIndent removes the common leading spaces from all lines in a multiline string.
Applying trimIndent to a multiline string removes the smallest number of spaces that appear at the start of every line: val text = """ Hello, Kotlin! """.trimIndent() Now the string has no leading spaces before 'Hello' and 'Kotlin!'.
Result
The string contains: Hello, Kotlin!
trimIndent smartly removes only the shared indentation, preserving the relative formatting inside the string.
4
IntermediateHow trimIndent handles uneven indentation
🤔Before reading on: If one line is less indented than others, does trimIndent remove spaces based on the smallest indent or the largest? Commit to your answer.
Concept: trimIndent removes spaces based on the smallest indentation among all non-blank lines.
Consider this string: val text = """ Hello, Kotlin! """.trimIndent() The first line has 4 spaces, the second has 6. trimIndent removes 4 spaces from each line, leaving: Hello, Kotlin!
Result
The string contains: Hello, Kotlin!
trimIndent preserves relative indentation by removing only the minimum common spaces, keeping the intended structure.
5
IntermediateBlank lines and trimIndent behavior
🤔
Concept: How trimIndent treats blank lines when calculating indentation.
Blank lines are ignored when determining the common indent. For example: val text = """ Hello, Kotlin! """.trimIndent() The blank line does not affect the amount of spaces removed.
Result
The string contains: Hello, Kotlin!
Ignoring blank lines prevents unexpected removal of spaces and keeps blank lines intact.
6
AdvancedtrimIndent vs trimMargin for indentation control
🤔Before reading on: Do you think trimIndent and trimMargin do the same thing? Commit to your answer.
Concept: trimIndent removes common leading spaces, while trimMargin removes a margin prefix from each line.
trimMargin lets you define a margin prefix (default '|') to mark where the text starts: val text = """ |Hello, |Kotlin! """.trimMargin() This removes everything before '|' on each line. trimIndent removes spaces without needing a prefix.
Result
trimMargin output: Hello, Kotlin!
Knowing when to use trimIndent or trimMargin helps you format multiline strings flexibly.
7
ExpertInternal implementation of trimIndent
🤔Before reading on: Do you think trimIndent scans all lines first or processes line by line? Commit to your answer.
Concept: trimIndent first finds the smallest indent among all lines, then removes that indent from each line.
Internally, trimIndent splits the string into lines, ignores blank lines, calculates the minimum leading spaces, then removes that many spaces from each line. This two-step process ensures consistent indentation removal. It preserves relative indentation and blank lines.
Result
trimIndent produces a clean string with intended formatting.
Understanding this two-step process explains why trimIndent preserves relative indentation and handles blank lines gracefully.
Under the Hood
trimIndent works by splitting the multiline string into individual lines. It ignores blank lines and calculates the smallest number of leading spaces common to all non-blank lines. Then it removes exactly that number of spaces from the start of each line. This preserves the relative indentation inside the string while removing unwanted leading spaces caused by code formatting.
Why designed this way?
Kotlin was designed to keep code readable and strings easy to write. Without trimIndent, developers had to manually remove spaces or write ugly concatenations. The approach balances preserving the intended text layout with allowing code indentation. Alternatives like trimMargin require special margin characters, but trimIndent works naturally without extra syntax.
Multiline string with indentation:
┌───────────────────────────────┐
│     """                     │
│         Hello,               │
│           Kotlin!            │
│     """.trimIndent()        │
└───────────────────────────────┘

Step 1: Split lines → ["    Hello,", "      Kotlin!"]
Step 2: Find smallest indent → 4 spaces
Step 3: Remove 4 spaces from each line → ["Hello,", "  Kotlin!"]
Step 4: Join lines → "Hello,\n  Kotlin!"
Myth Busters - 4 Common Misconceptions
Quick: Does trimIndent remove all leading spaces from every line? Commit yes or no.
Common Belief:trimIndent removes all leading spaces from every line in the string.
Tap to reveal reality
Reality:trimIndent only removes the smallest common number of leading spaces shared by all non-blank lines, preserving relative indentation.
Why it matters:Assuming it removes all spaces can lead to unexpected formatting loss, breaking the intended structure of the string.
Quick: Does trimIndent affect blank lines inside the string? Commit yes or no.
Common Belief:trimIndent removes spaces from blank lines as well.
Tap to reveal reality
Reality:trimIndent ignores blank lines when calculating indentation and leaves them unchanged.
Why it matters:Misunderstanding this can cause confusion when blank lines appear to have inconsistent indentation.
Quick: Is trimIndent the same as trimMargin? Commit yes or no.
Common Belief:trimIndent and trimMargin do the same thing and can be used interchangeably.
Tap to reveal reality
Reality:trimIndent removes common leading spaces, while trimMargin removes a specific margin prefix from each line.
Why it matters:Using the wrong function can cause formatting errors or require unnecessary margin characters.
Quick: Can trimIndent be used on single-line strings? Commit yes or no.
Common Belief:trimIndent only works on multiline strings.
Tap to reveal reality
Reality:trimIndent can be called on any string, but it only affects strings with multiple lines.
Why it matters:Thinking it only works on multiline strings limits its use in cleaning up strings with accidental indentation.
Expert Zone
1
trimIndent preserves relative indentation, which is crucial when formatting nested text like code or lists.
2
Blank lines are ignored in indentation calculation but remain in the output, allowing intentional spacing.
3
trimIndent does not modify trailing spaces, so trailing whitespace inside lines remains untouched.
When NOT to use
Avoid trimIndent when you want to remove a specific margin prefix or marker; use trimMargin instead. Also, if you need to remove all leading spaces regardless of common indentation, manual trimming or regex may be necessary.
Production Patterns
In production, trimIndent is often used to embed formatted text like SQL queries, JSON, or XML templates directly in code without extra concatenation. It helps keep code clean and readable while preserving the exact text format needed for external systems.
Connections
Text formatting in word processors
Both handle indentation and alignment of multiline text blocks.
Understanding how trimIndent works is similar to how word processors adjust paragraph indentation to keep text aligned and readable.
Code block indentation in programming languages
trimIndent preserves relative indentation like code blocks preserve nested structure.
Knowing trimIndent’s behavior helps understand how indentation defines structure in code and text.
Data serialization formats (e.g., JSON, YAML)
Proper indentation is critical for readability and correctness in these formats.
Using trimIndent to format multiline strings helps produce valid, readable serialized data embedded in code.
Common Pitfalls
#1Including unwanted spaces due to code indentation.
Wrong approach:val text = """ Hello, Kotlin! """
Correct approach:val text = """ Hello, Kotlin! """.trimIndent()
Root cause:Not realizing that code indentation becomes part of the string content.
#2Expecting trimIndent to remove all leading spaces.
Wrong approach:val text = """ Hello, Kotlin! """.trimIndent() // expecting no spaces at all
Correct approach:val text = """ Hello, Kotlin! """.trimIndent() // removes only 4 spaces, preserving relative indent
Root cause:Misunderstanding that trimIndent removes only the smallest common indent.
#3Using trimIndent when trimMargin is needed.
Wrong approach:val text = """ |Hello, |Kotlin! """.trimIndent()
Correct approach:val text = """ |Hello, |Kotlin! """.trimMargin()
Root cause:Confusing the purpose of trimIndent and trimMargin functions.
Key Takeaways
Multiline strings let you write text across lines without special characters.
Code indentation adds spaces to multiline strings unless cleaned up.
trimIndent removes the smallest common leading spaces from all lines, preserving relative indentation.
trimIndent ignores blank lines when calculating indentation, keeping them intact.
Choosing between trimIndent and trimMargin depends on whether you want to remove common spaces or a margin prefix.