Kotlin add carriage return into multiline string

Tom Tresansky picture Tom Tresansky · Feb 22, 2018 · Viewed 20.2k times · Source

In Kotlin, when I build a multiline string like this:

value expected = """
                |digraph Test {
                |${'\t'}Empty1;
                |${'\t'}Empty2;
                |}
                |""".trimMargin()

I see that the string lacks carriage return characters (ASCII code 13) when I output it via:

println("Expected bytes")
println(expected.toByteArray().contentToString())

Output:

Expected bytes
[100, 105, 103, 114, 97, 112, 104, 32, 84, 101, 115, 116, 32, 123, 10, 9, 69, 109, 112, 116, 121, 49, 59, 10, 9, 69, 109, 112, 116, 121, 50, 59, 10, 125, 10]

When some code I'm trying to unit test builds the same String via a PrintWriter it delineates lines via the lineSeparator property:

/* 
 * Line separator string.  This is the value of the line.separator
 * property at the moment that the stream was created.
 */

So I end up with a string which looks the same in output, but is composed of different bytes and thus is not equal:

Actual bytes
[100, 105, 103, 114, 97, 112, 104, 32, 84, 101, 115, 116, 32, 123, 13, 10, 9, 69, 109, 112, 116, 121, 49, 59, 13, 10, 9, 69, 109, 112, 116, 121, 50, 59, 13, 10, 125, 13, 10]

Is there a better way to address this during string declaration than splitting my multiline string into concatenated stringlets which can each be suffixed with char(13)?

Alternately, I'd like to do something like:

value expected = """
                |digraph Test {
                |${'\t'}Empty1;
                |${'\t'}Empty2;
                |}
                |""".trimMargin().useLineSeparator(System.getProperty("line.separator"))

or .replaceAll() or such.

Does any standard method exist, or should I add my own extension function to String?

Answer

Ahamed Mujeeb picture Ahamed Mujeeb · Nov 17, 2019

This did the trick.

    System.lineSeparator()