Multiline string literal indent handling is unconvient


#1

I want to print:

line line

I must write:

class TestMultiLine {
    Test fun test() {
        println("""line
line""")
    }
}

This way breaks code formatting.

Please, consider Fantom approach:

class TestMultiLine {
    Test fun test() {
        println("""line
                   line""")
    }
}

#2

Maybe something like this would be good enough for you?  It's inspired by the same method `stripMargin` in Scala:

fun String.stripMargin(): String {
  val lines = this.split(“n”)
  return lines map { it.replaceAll("^\s*|", “”) } join “n”
}


fun main(args: Array<String>) {
  println(""“Apples, oranges,
  |bananas, kiwis,
  |  avocados, tomatoes”"".stripMargin())


}


You could shorten the name, or make it a val so no need for parentheses.

Rob


#3

I’m not a fan of Fantom’s approach, but I would like to see something like Scala`s stripMargin in the standard library.


#4

There are two convenient functions in stdlib for stripping margin from multiline strings: trimMargin and trimIndent.

	fun test() {
        println("""|line
                   |line""".trimMargin())
        
        println("""
            line
            line
            """.trimIndent())        
    }

#5

The problem with that approach is the trimming is done at run time. It would be nice to have a way to tell the compiler to do it at compile time.


#6

This seems like an ideal candidate for a compiler (not JVM) intrinsic. The nice thing about standard libraries is that functions from it can be replaced by intrinsics if so desired. Their API’s are kind of frozen by default anyway.


#7

I completely agree. A lot of time I write SQLs, HTML and other similar things in my code. Would be very nice to have such a functionality. And multiline string keeping extra left spaces is just crazy. This create a very strange code or a very strange string. I don’t know what would be the best rule the follow when removing this extra spaces, but I am sure it is possible to figure out some solution.

Leonardo Priori


#8

Xtend has solved this really nicely:
https://eclipse.org/xtend/documentation/203_xtend_expressions.html#templates

Perhaps some inspiration there?


#9

The “solution” is in the String.trim... functions that you can use to trim as desired. If these functions could now be defined as constexpr and evaluated at compile time your problem would go away. Alternatively, it may be possible to have a compiler plugin that recognizes these specific function calls and in case of a compile time constant parameter replaces it with the result of calling the function - constexpr is a lot cleaner as it is not limited to “special cases”.