显然scala不支持数字文字中的jdk7和更高版本的下划线?
我正在使用jdk 8
scala> System.getProperty("java.version")
res0: String = 1.8.0_40
在这里,我们尝试使用jdk7(及更高版本)数字文字:
scala> val x = 1_000_000
<console>:1: error: Invalid literal number
val x = 1_000_000
^
这有scala语言选项吗?
在Scala土地上你可能已经看过如下:
s"My name is $firstName"
和
sql"select id, name from members where id = ${id}"
没有理由没有:
i"1 000 000"
甚至:
animal"Dog" // checks that Dog is on the list of animal words
Scala库中内置了i
字符串插值,但您可以使用:
implicit class IntContext(val sc: StringContext) {
def i(args: Any*): Int = {
val orig = sc.s(args: _*)
orig.replace(" ", "").toInt
}
}
i"1 000 000" // res0: Int = 1000000
请注意,启动Scala 2.13
,下划线被接受为数字文字分隔符:
val x = 1_000_000
// x: Int = 1000000
val pi = 3_14e-0_2
// pi: Double = 3.14