Multiline strings are very useful. But sometimes we want use the multiline string without the leading spaces that are added because of code formatting. To remove leading spaces we can use the trimIndent method. This method will find the least amount of leading spaces and removes that amount of spaces from each line. Also a first and last empty line are removed.

If we want a bit more control we can also add a character to the start of each line to show where the line starts. And then we use the method trimMargin and all spaces before that character are removed. The default character is the pipe symbol, |, but we can also define our own and pass it as argument to the trimMargin method.

In the following example code we use the trimIndent and trimMargin methods:

// trimIndent will remove spaces from the beginning
// of the line based on the least number of spaces.
// The first and last empty line are also removed
// from the string.
fun createText(): String {
    return """
        Multiline string
          with simple 2 spaces
        indentation.
    """.trimIndent()
}

assert(createText() == """Multiline string
  with simple 2 spaces
indentation.""")

// trimMargin will trim all spaces before
// the default margin character |.
val languages = """
    |Kotlin
    |Groovy
    |Clojure
      |Java
""".trimMargin()

assert(languages == """Kotlin
Groovy
Clojure
Java""")

// We can use our own margin character by
// specifying the character as argument
// to the trimMargin method.
val buildTools = """
    >Gradle
    >Maven
      >SBT
    >Leiningen
""".trimMargin(">")

assert(buildTools == """Gradle
Maven
SBT
Leiningen""")

Written with Kotlin 1.7.20.

shadow-left