Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using asInstanceOf to convert Any to Double

Tags:

scala

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:

 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).

like image 403
user3120635 Avatar asked Dec 19 '13 20:12

user3120635


2 Answers

Scala's asInstanceOf is its name for casting. 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)
like image 100
Randall Schulz Avatar answered Oct 30 '22 22:10

Randall Schulz


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 here for another way of doing it.

like image 20
ValarDohaeris Avatar answered Oct 31 '22 00:10

ValarDohaeris