Reputation: 45765
Let's say I don't have the option of using [T: Numeric]
type class for some reason.
Is there a way given an "Any" to test if it is a "Number" without using the above?
EDIT: thanks to Lee's comment, it's apparently as easy as in Java: x.isInstanceOf[Number]
.
My understanding of why it works is: x:Any = 1
is basically in runtime a java.lang.Integer
which in turn implements java.lang.Number
Upvotes: 0
Views: 54
Reputation: 893
val a = "hello"
val b = 1.34
toNumericOption(a) // None
toNumericOption(b) //Some(1.34)
def toNumericOption(x: Any) = x match {
case n: java.lang.Number => Some(n)
case _ => None
}
You can use this to convert to an Option
Upvotes: 5