Rushabh Patel
Rushabh Patel

Reputation: 2764

Casting error from Option[Double] to Double in scala

I am facing a problem in casting from Option[Double] to Double. I am getting the following exception error:

scala.Some cannot be cast to java.lang.Double

val ty = ttnew.distinct().leftOuterJoin(rank).map{ case ((key),(c,d)) => (key,c._1,c._2,c._3,d.getOrElse(Double).asInstanceOf[Double]) }

Please Help!

Upvotes: 1

Views: 7241

Answers (2)

pedrorijo91
pedrorijo91

Reputation: 7845

that's not how you deal with Option. Use .getOrElse or a .map

val ty=ttnew.distinct().leftOuterJoin(rank).map{ case ((key),(c,d)) => (key,c._1,c._2,c._3,d.getOrElse(Double).asInstanceOf[Double]) }

probably (in this situation) you will want to do d.getOrElse(<a-good-default-value-like-zero-maybe>)

other situations maybe you want to propagate the meaning of Option (the value may not exist), and in those cases you should use the .map:

val res: Option[String] = optionalDouble.map(doubleValue => callSomeFunctionThatConvertsDoubleToString(value))

you can even do other things using pattern matching and extractors. for instance, using .collect (it's a .map, but there may be cases not covered):

val ty=ttnew.distinct().leftOuterJoin(rank).collect{ case ((key),(c,Some(d))) => (key,c._1,c._2,c._3,d) }

Upvotes: 5

Gabriele Petronella
Gabriele Petronella

Reputation: 108101

d.getOrElse(Double).asInstanceOf[Double]

makes no sense.

Assuming d is an Option[Double] if you want to have a Double you cannot cast it, you need to get the value "out of" the Option.

getOrElse allows you to get the value if present, and provide a fallback value if absent (i.e. None).

For example:

d.getOrElse(0) // 0, or anything that makes sense as a fallback

If d has type Option[Double] then d.getOrElse(0) has type Double.

Upvotes: 11

Related Questions