2

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.

WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560

2 Answers2

5

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())
Gábor Bakos
  • 8,982
  • 52
  • 35
  • 52
2

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)
Community
  • 1
  • 1
Dimitri
  • 1,786
  • 14
  • 22
  • I am OK with ideas like this. There are times I do not want fancy/long code: in this case it is within a Testing Class and efficiency is not a criterion. – WestCoastProjects Nov 27 '14 at 23:07