简体   繁体   English

使用asInstanceOf将Any转换为Double

[英]Using asInstanceOf to convert Any to Double

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. 第一个是String,其余是数字(Int或Double),所以我使用Any *来获取参数。 I would like to treat the numbers uniformly as Doubles, but I cannot just use asInstanceOf[Double] on the numeric arguments. 我想将数字统一地视为双打,但我不能在数字参数上使用asInstanceOf [Double]。 For example: 例如:

 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). (该功能需要添加所有数字)。

Scala's asInstanceOf is its name for casting. Scala的asInstanceOf是它的铸造名称。 Casting is not converting. 铸造不是转换。

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)

Here is a slight simplification of Randall's answer: 以下是Randall答案的略微简化:

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 here for another way of doing it. 在Scala中匹配任何类型的数字都会变得有点棘手,请参阅此处了解其他方法。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM