Kotlin's multiline string handling is wonderful in so many ways, and it's ability to .trimIndent() allows you to keep a string literal indented with the rest of the code like so:
fun main(args: Array<String>) {
    val myString = """
    hello
    world
""".trimIndent()
println(myString)
Will print out:
hello
world
without the literal indents present in the code. But this breaks down when using Kotlin's powerful string templating system if the value being inserted is multiline:
fun main(args: Array<String>) {
    val myString = """
    hello
    world
""".trimIndent()
    
    println("""
        teststring2
        $myString
    """.trimIndent())
}
will print out
            teststring2
            hello
world
This appears to happen because the world is on a new line and doesn't receive the indentation that hello gets.  Is there an elegant way to handle this?
This is a common problem in practice, not trimIndent()'s problem. @gidds has explained it very clearly. If you want to achieve what you want, you can use trimMargin().
fun main(args: Array<String>) {
    val myString = """
    hello
    world
""".trimIndent()
    
    println("""
        |teststring2
        |$myString
    """.trimMargin())
}
Output:
teststring2
hello
world
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With