多行字符串文字仅在REPL和Worksheet中表现合理 [英] Multi-line string literals behave sane only in REPL and Worksheet

查看:71
本文介绍了多行字符串文字仅在REPL和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.lengthb.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆