Search code examples
scala

Get Option value or throw an exception


Given an Option, what is the idiomatic way to get its value or throw an exception trying?

def foo() : String = {
  val x : Option[String] = ...
  x.getOrException()
}

Solution

  • (EDIT: this is not the best or most idiomatic way to do it. I wrote it when I was not familiar with Scala. I leave it here for an example of how not to do it. Nowadays I would do as @TravisBrown)

    I think it really boils down to two things:

    • how sure are you that the value is there?
    • how do you want to react if it isn't?

    If at that point in your code you expect the value to be there, and in the remote case that it isn't you want your program to fail fast, then I would only do a normal get and let Scala throw a NoSuchElementException if there was no value:

    def foo() : String = {
      val x : Option[String] = ...
      x.get
    }
    

    If you want to handle the case differently (throw your own exception) I think a more elegant way would look like this:

    def foo(): String = {
      val x: Option[String] = None
      x match {
        case Some(value) => value
        case None => throw new MyRuntimeException("blah")
      }
    } 
    

    And of course if you want to supply your own alternative value for the case that the Option is None you would just use getOrElse:

    def foo(): String = {
      val x: Option[String] = None
      x.getOrElse("my alternative value")
    }