Reputation: 263320
Are line breaks in raw strings platform-dependent?
val a = "one\ntwo";
val b = """one
two"""
println(a == b)
In other words, is the println
statement above guaranteed to print true
or not?
Upvotes: 7
Views: 2790
Reputation: 47299
It appears to be intentional in that it compiles down to the newline character only. This forum post and the response comment from Roman Elizarov clarifies this.
""" -first line -second line """.trimIndent() ```
compiles to
"-first line\n-secondline"
instead of
"-first line\r\n-second line"
Is this by design? Is there any official documentation about line separators in triple-quoted strings?
And the response:
Yes. It is so by design. There is a key requirement that behavior of the code should not depend on the platform it was compiled on. ...
The follow up action from the thread is KT-56021, an issue to document this case:
KT-56021: Docs: Mention that multiline strings always use NL separators regardless of the platform.
Upvotes: 0
Reputation: 10605
I would not consider it guarantee that a
and b
are equal. The Spec has this to say about raw string literals:
Kotlin has two types of string literals: escaped strings that may have escaped characters in them and raw strings that can contain newlines and arbitrary text.
So, if I were writing code to work across platforms, I would be explicit (at least until they are).
Upvotes: 0
Reputation: 89628
Unfortunately, I couldn't find any sources specifically stating this. It feels like something that should be in the docs.
There is, however, the intention action in IntelliJ that converts a raw string to an ordinary string. I think it should be safe to assume that this action should not change the meaning of your code (or if it does, that should be filed as a bug). If you try this on a raw string with a newline in it, you can see that it replaces the newline with a \n
character.
You can see the source of the action here, and a test for it that expects it to convert the newline to \n
here (before) and here (after).
Edit: here's a comment on an issue about raw strings that (as far as I understand) states that a raw string has \n
line endings in it.
Upvotes: 1