25

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?

Tom Tresansky
  • 19,364
  • 17
  • 93
  • 129

2 Answers2

40

This did the trick.

    System.lineSeparator()
Ahamed Mujeeb
  • 615
  • 1
  • 8
  • 13
20

Kotlin multiline strings are always compiled into string literals which use \n as the line separator. If you need to have the platform-dependent line separator, you can do replace("\n", System.getProperty("line.separator")).

As of Kotlin 1.2, there is no standard library method for this, so you should define your own extension function if you're using this frequently.

yole
  • 92,896
  • 20
  • 260
  • 197