简体   繁体   English

多行字符串文字仅在REPL和Worksheet中表现良好

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

REPL: 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: 正常的Scala代码:

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? 为什么比较在REPL和Worksheet中产生true,但在正常的Scala代码中是false?


Interesting, b appears to be one char longer than a , so I printed the Unicode values: 有趣的是, b似乎比a长一个字符,所以我打印了Unicode值:

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. 我在Windows上使用Eclipse。

I guess it's because of the source file encoding . 我想这是因为源文件编码

Try to check a.toList.length and b.toList.length . 尝试检查a.toList.lengthb.toList.length It seems b == "hello\\r\\nworld" . 看来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 . 实际上你会得到你在"""之间的源文件中的确切内容。如果有\\r\\n你将在你的String得到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM