Casting an option to its original type

Hello all,

Suppose I have a
case class foo { id: String ; num: Int …}
and a function foobar that returns a Option[foo]
How can I cast the value returned by foobar to a foo in order to access the fields of foo ?

Thanks for your help.


You shouldn’t cast, you should .map.

Basically, Scala is trying to make you think more carefully about what to do if you don’t have a Foo here. You can’t just brush it under the rug – you have to tell it what to do.

So if you have code that should only run if you do have a Foo, you say:

foobar().map { myfoo =>
  // Here, "myfoo" is a value of type Foo

In this case, it just won’t do anything if the result was None.

Or, if you have a default Foo to use if the Option is None, you can say:

val myfoo: Foo = foobar().getOrElse(myDefaultFooValue)

Note that there is a .get method on Option that will simply hand you the value if it’s there, and throw an exception if it isn’t, but that’s considered bad practice in most cases unless it is absolutely guaranteed that foobar() will return a value.

1 Like

Thanks for your explanations.

Best regards,


----- Mail original -----

makes sense thanks.