I am trying to use the Option.getOrElse()
method but it returns etiher Any
or ScalaObject
instead of an instance of the correct class that the Option
was parametrized with. I can't find any mention about this problem and it does not seem like it should be there. What am I doing wrong?
class MyClass {
def isOk = true
}
val myVal = Some(new MyClass) // :Option[MyClass]
val check = myVal.getOrElse(false).isOk
Can't call the isOk
method because it tries calling it upon Any
.
You are trying to call method isOk
on base class of MyClass
and Boolean
(Any
).
Try this:
scala> class MyClass(b: Boolean) { def isOk = b }
defined class MyClass
scala> val myVal = Some(new MyClass(true))
myVal: Some[MyClass] = Some(MyClass@35d56bbe)
scala> myVal.map{_.isOk}.getOrElse(false)
res0: Boolean = true
scala> myVal.getOrElse(new MyClass(false)).isOk
res1: Boolean = true