scala 使用 asInstanceOf 将 Any 转换为 Double

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20691388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:56:58  来源:igfitidea点击:

Using asInstanceOf to convert Any to Double

scala

提问by user3120635

I have a function that takes a variable number of arguments. The first is a String and the rest are numbers (either Int or Double) so I am using Any* to get the arguments. I would like to treat the numbers uniformly as Doubles, but I cannot just use asInstanceOf[Double] on the numeric arguments. For example:

我有一个接受可变数量参数的函数。第一个是字符串,其余是数字(Int 或 Double),所以我使用 Any* 来获取参数。我想将数字统一视为双精度数,但我不能只在数字参数上使用 asInstanceOf[Double]。例如:

 val arr = Array("varargs list of numbers", 3, 4.2, 5)
 val d = arr(1).asInstanceOf[Double]

gives:

给出:

 java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double

Is there a way to do this? (The function needs to add up all the numbers).

有没有办法做到这一点?(该函数需要将所有数字相加)。

回答by Randall Schulz

Scala's asInstanceOfis its name for casting. Casting is not converting.

ScalaasInstanceOf是它的名称,用于转换。铸造不是转换。

What you want can be accomplished like this:

你想要的可以这样完成:

val mongrel = List("comment", 1, 4.0f, 9.00d)
val nums = mongrel collect { case i: Int => i case f: Float => f case d: Double => d }
val sumOfNums = nums.foldLeft(0.0) ((sum, num) => sum + num)

回答by ValarDohaeris

Here is a slight simplification of Randall's answer:

这是兰德尔的回答的稍微简化:

val mongrel = List("comment", 1, 4.0f, 9.00d)
val nums = mongrel collect { case i: java.lang.Number => i.doubleValue() }
val sumOfNums = nums.sum

Matching for any kind of number turns out to be a little tricky in Scala, see herefor another way of doing it.

在 Scala 中匹配任何类型的数字都有些棘手,请参阅此处了解另一种方法。

回答by tmbo

When there is a need to handle different types, you should avoid casting them and instead use a pattern match. To add up all Double's and Int's of an array you could use:

当需要处理不同的类型时,您应该避免强制转换它们,而是使用模式匹配。要将数组的所有 Double 和 Int 相加,您可以使用:

val array = Array("varargs list of numbers", 3, 4.2, 5)

array.foldLeft(0.0){ 
  case (s, i: Int) => s + i
  case (s, d: Double) => s + d
  case (s, _) => s
}

The pattern match allows you to treat each different type separately and avoids running into ClassCastExceptions.

模式匹配允许您分别处理每种不同的类型并避免遇到ClassCastExceptions.

回答by Rob N

Stepping back for a moment, might it be easier to have the function take Double*instead of Any*?

退后一步,让函数Double*代替会更容易Any*吗?

scala> def foo(str: String, nums: Double*) { 
    nums foreach { n => println(s"num: $n, class:   ${n.getClass}") } 
}
foo: (str: String, nums: Double*)Unit

scala> foo("", 1, 2.3)
num: 1.0, class: double
num: 2.3, class: double