I need to do some raw data parsing and I am forced to work with Any
type.
If the data I read is in any numeric format (Int
/Double
/Long
/...) I need to convert it to Double
, otherwise (eg. String
) I need to leave it empty.
This is what I came up with:
def extractDouble(expectedNumber: Any): Option[Double] = expectedNumber match {
case i: Int => Some(i.toDouble)
case l: Long => Some(l.toDouble)
case d: Double => Some(d)
case _ => None
}
This obviously doesn't look even decently. Is there any better way to deal with this in Scala?
Once you lost your type information at compile time, as it happens to be in your case since your input type is Any
as part of its requirements, there is no more options than inspecting expectedNumber
at run time with isInstanceOf
.
That is masked by the implementation of type pattern matching you are doing in your proposed solution. And I think that is the best solution in your case.
However, there is an alternative which is using Try
over and transforming it into an Option
. e.g:
Try(expectedNumber.toString.toDouble).toOption
That's a dirty solution in so many ways (not efficient at all, using exceptions to control flow, ...) that I would definetively use your first approach
It is certainly possible, as indicated in this answer:
Use java.lang.Number
to match with your case type.
def extractDouble(x: Any): Option[Double] = x match {
case n: java.lang.Number => Some(n.doubleValue())
case _ => None
}
Note that this also works for instances of BigDecimal
and BigInteger
, be it scala.math.BigDecimal
or java.math.BigDecimal
.
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