我试图创建一个包含所有 Int
、Long
和 Double
类型的数组。但是,我发现 Long
和 Int
类型会自动转换为 Double
。
这是一个最小的例子,
object HelloWorld {
def main(args: Array[String]): Unit = {
val types = Array[Byte]('i', 'l', 'd', 'd')
val array = Array[String]("1", "2000000", "20.0", "2020.0")
val values = array.zip(types) map { case (s, t) =>
t match {
case 'i' => s.toInt
case 'l' => s.toLong
case 'd' => s.toDouble
}
}
values.foreach { println }
}
}
结果是
1.0
2000000.0
20.0
2020.0
如何避免这种转换?谢谢。
最佳答案
表达式
t match {
case 'i' => s.toInt
case 'l' => s.toLong
case 'd' => s.toDouble
}
推断为 Double
因为 Scala 2 计算弱最小上限。一种选择是使用类型归属来明确告诉编译器常规最小上限,例如,
(t match {
case 'i' => s.toInt
case 'l' => s.toLong
case 'd' => s.toDouble
}): AnyVal
Scala 3 drops弱一致性的概念
drops the general notion of weak conformance, and instead keeps one rule: Int literals are adapted to other numeric types if necessary.
因此您的示例将按预期工作。
关于scala - 创建包含 AnyVal 类型的数组时如何抑制从 Long 到 Double 的自动转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64432911/