多行字符串文字仅在REPL和Worksheet中表现合理 [英] Multi-line string literals behave sane only in REPL and Worksheet
问题描述
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
工作表:
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和工作表中比较结果为true,而在正常的Scala代码中为false?
Why does the comparison yield true in the REPL and in the Worksheet, but false in normal Scala code?
有趣的是,b
似乎比a
长一个字符,所以我打印了Unicode值:
Interesting, b
appears to be one char longer than a
, so I printed the Unicode values:
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.
Does that mean multi-line string literals have platform-dependent values? I use Eclipse on Windows.
推荐答案
我想这是因为源文件编码.
尝试检查a.toList.length
和b.toList.length
.似乎是b == "hello\r\nworld"
.
多行字符串文字值不取决于平台,而是取决于源文件的编码.实际上,您将获得"""
之间的源文件中的所有内容.如果有\r\n
,您会在String
中找到它.
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
.
这篇关于多行字符串文字仅在REPL和Worksheet中表现合理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!