简体   繁体   English

使用asInstanceOf将Any转换为Double吗?

[英]Convert Any to Double using asInstanceOf?

Is there a supported way to achieve a conversion of any numeric type to a double. 是否有支持将任何数字类型转换为双精度类型的方法。 Eg 例如

   val i = 12345
   val f = 1234.5F
   val d = 1234.5D
   val arr = Array[Any](i,f,d)
   val anotherD = arr(0).asInstanceOf[Numeric].toDouble

Naturally the above code is not correct as given - since Numeric requires Type arguments. 当然,上面的代码不正确 - 因为Numeric需要Type参数。

scala>        val i = 12345
i: Int = 12345

scala>        val f = 1234.5F
f: Float = 1234.5

scala>        val d = 1234.5D
d: Double = 1234.5

scala>        val arr = Array[Any](i,f,d)
arr: Array[Any] = Array(12345, 1234.5, 1234.5)

scala>        val anotherD = arr(0).asInstanceOf[Numeric].toDouble
<console>:11: error: type Numeric takes type parameters
              val anotherD = arr(0).asInstanceOf[Numeric].toDouble

Now I realize the above may be achieved via match/case , along the following lines: 现在,我意识到可以通过match / case,通过以下几行实现以上目标:

  (a, e) match {
    case (a : Double, e : Double) =>
        Math.abs(a - e) <= CompareTol
    case (a : Float, e : Float) =>
        Math.abs(a - e) <= CompareTol
    .. etc

But I was wondering if there were a means to more compactly express the operation. 但是我想知道是否有一种手段可以更紧凑地表达这一行动。 This code is within TEST classes and efficiency is not an important criterion. 该代码在TEST类之内,效率不是重要的标准。 Specifically: reflection calls are OK. 具体来说:反射调用是可以的。 Thanks. 谢谢。

I assume you are on the JVM. 我假设你在JVM上。 The Number class does like what you want to achieve with the doubleValue method: Number类与您想要使用doubleValue方法实现的内容类似:

val arr = Array[Number](i,f,d)
val ds = arr.map(_.doubleValue())

This is horrible, and probably not efficient , but it works (on your example) :p 这太可怕了, 可能效率不高 ,但它有效(在你的例子中):p

scala> import scala.language.reflectiveCalls
import scala.language.reflectiveCalls

scala> arr.map(_.asInstanceOf[{ def toDouble: Double }].toDouble)
res2: Array[Double] = Array(12345.0, 1234.5, 1234.5)

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

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