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).
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With