Hacker News new | ask | show | jobs
by dlwh 5553 days ago
Option can occasionally be a pain to handle, I admit. But typically it works really well for me.

The standard Haskell-ish approach is to use for-comprehensions:

val maybeWebpage = for(foo <- maybeFoo) yield { // do things with foo, yielding some resulting webpage snippet or whatever }

As he points out, this can cause Options to propagate, but it does allow you to defer dealing with the exception until later. You can reasonably argue that it leads to better modularity, since you can dump all of your error handling in the same function, and different callers can decide how they want to process errors.

Nevertheless, the OP wants a getOrThrow method (which he could of course add via implicits), but you can also just use getOrElse, which usually returns some other expression in the case of None, but since throw is just an expression in Scala, you can use it there:

scala> val foo = Some("foo").getOrElse(throw new Exception("whatever")) foo: java.lang.String = foo

scala> val foo = None.getOrElse(throw new Exception("whatever")) java.lang.Exception: whatever at $anonfun$1.apply(<console>:5) at $anonfun$1.apply(<console>:5) at scala.Option.getOrElse(Option.scala:104) at .<init>(<console>:5)