WestCoastProjects
WestCoastProjects

Reputation: 63231

Convert Any to Double using asInstanceOf?

Is there a supported way to achieve a conversion of any numeric type to a double. E.g.

   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.

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:

  (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. Specifically: reflection calls are OK. Thanks.

Upvotes: 2

Views: 2133

Answers (2)

G&#225;bor Bakos
G&#225;bor Bakos

Reputation: 9100

I assume you are on the JVM. The Number class does like what you want to achieve with the doubleValue method:

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

Upvotes: 5

Dimitri
Dimitri

Reputation: 1786

This is horrible, and probably not efficient, but it works (on your example) :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)

Upvotes: 2

Related Questions