4

回复:

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

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

scala> a == b
res0: Boolean = true

工作表:

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

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

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

普通的 Scala 代码:

val a = "hello\nworld"

val b = """hello
world"""

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

输出:

hello
world
hello
world
false

为什么在 REPL 和 Worksheet 中比较结果为真,但在普通 Scala 代码中为假?


有趣的是,b似乎比 长一个字符a,所以我打印了 Unicode 值:

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

输出:

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)

这是否意味着多行字符串文字具有平台相关的值?我在 Windows 上使用 Eclipse。

4

1 回答 1

4

我想这是因为源文件编码

尝试检查a.toList.lengthb.toList.length。看来b == "hello\r\nworld"

多行字符串文字值不取决于平台,而是取决于源文件的编码。实际上你会得到你在源文件中所拥有的""". 如果有,\r\n你会在你的String.

于 2013-06-19T11:46:31.077 回答