Multi-line string literals behave sane only in REPL and Worksheet

旧巷老猫 提交于 2019-12-10 20:59:15

问题


REPL:

scala> val a = "hello\nworld"
a: String = 
hello
world

scala> val b = """hello
     | world"""
b: String = 
hello
world

scala> a == b
res0: Boolean = true

Worksheet:

val a = "hello\nworld"                        //> a  : String = hello
                                              //| world

val b = """hello
world"""                                      //> b  : String = hello
                                              //| world

a == b                                        //> res0: Boolean = true

Normal Scala code:

val a = "hello\nworld"

val b = """hello
world"""

println(a)
println(b)
println(a == b)

Output:

hello
world
hello
world
false

Why does the comparison yield true in the REPL and in the Worksheet, but false in normal Scala code?


Interesting, b appears to be one char longer than a, so I printed the Unicode values:

println(a.map(_.toInt))
println(b.map(_.toInt))

Output:

Vector(104, 101, 108, 108, 111, 10, 119, 111, 114, 108, 100)
Vector(104, 101, 108, 108, 111, 13, 10, 119, 111, 114, 108, 100)

Does that mean multi-line string literals have platform-dependent values? I use Eclipse on Windows.


回答1:


I guess it's because of the source file encoding.

Try to check a.toList.length and b.toList.length. It seems b == "hello\r\nworld".

Multi-line string literal value depends not on the platform, but on the encoding of the source file. Actually you'll get exactly what you have in the source file between """. If there is \r\n you'll get it in your String.



来源:https://stackoverflow.com/questions/17190242/multi-line-string-literals-behave-sane-only-in-repl-and-worksheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!