[英]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和Worksheet中產生true,但在正常的Scala代碼中是false?
有趣的是, 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。
我想這是因為源文件編碼 。
嘗試檢查a.toList.length
和b.toList.length
。 看來b == "hello\\r\\nworld"
。
多行字符串文字值不取決於平台,而取決於源文件的編碼。 實際上你會得到你在"""
之間的源文件中的確切內容。如果有\\r\\n
你將在你的String
得到它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.