Apologies if this is a newbie question...
In Scala I understand that it is preferred to use an Option rather than returning null when you have a function which returns an instance but could potentially return nothing. I understand that this makes it better with regards to safety, because you are not passing null references around, and risking NullPointerException somewhere down the line.
However, is there a cleaner way to handle options than using pattern matching? The syntax I end up using is the following:
val optObj : Option[MyObject] = myFunctionThatReturnsOption
optObj match {
case Some(obj) => {
//my code using obj
}
case None => _
}
In reality all this doing is the equivalent of the Java version:
MyObject obj = myMethodThatCanReturnNull()
if (obj != null) {
//my code using obj
}
Is there some other way to avoid all this boilerplate in Scala when using Option instead of null references? All I want to do is execute a piece of code as long as the Option contains some object (i.e. is not None).
Optionis not about safety actually; it's about being able to handle missing values more easily.if (obj != null) {} else {}is definitely easy (arguably easier). The reason for using Scala is supporting such things in a typesafe and more correct way... :)if not null ... else nullis easy if you do it once but not if you have a chain of functions that can returnnull; futhermore, I'd even sayfoo.map(_.bar)is easier and shorter thanif (foo != null) foo.bar else null, and also much more readable after a while.