A succinct early exit trick for Option in Scala
I've realised that return
in Scala only apply to a method. This led me to a cool early exit trick that I use everywhere.
It looks a bit off because I, for some reason, think return
should have applied to the current lambda. But that's not the case in Scala.
Scenario: You have Option[A]
. You want to get the value or simply exit the method if the value is absent (i.e. None
)
Solution:
def someMethod(argOpt: Option[String]): Unit = {
val arg = argOpt.getOrElse { return }
... do something with arg ...
}
If argOpt
is None
, then it would just exit someMethod
. This piece of code avoids ugly nested code.
Just so you know: there is a suggestion against it here. Use it at your own risk.
Edit: Apparently, this is a controversial topic. You can see the discussion (which has some good alternatives!) on Reddit and this meme.