Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin string concatenation - preserving indents with multiline strings

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?

like image 585
J-bob Avatar asked Oct 30 '25 12:10

J-bob


1 Answers

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
like image 94
Vincent Sit Avatar answered Nov 01 '25 05:11

Vincent Sit