Search code examples
scalascala-option

Call a method on the value of Scala Option if present


I am trying to figure out the best way to refactor the following code to eliminate the use of Option.get(). I know that using the get method is considered bad practice.

if (myConnection.isDefined) {
  myConnection.get.close
}

where myConnection is of type Option[Connection]

getOrElse doesn't seem like it would work, because there is no "else" object to call the method on. If myConnection is None, then I don't want to do anything.

I suppose I could use forEach like:

myConnection.foreach{ c => c.close }

This would work, but it looks weird to me. In my case, myConnection would never contain more than one connection, and someone else later looking at my code might be led to believe that it could contain multiple connections.

Is there a better way to do this that is both concise and clear?


Solution

  • Typically, you would map over an Option to operate on its value.

    myConnection.map(c => c.close())
    

    or

    myConnection.map(close(_))
    

    which will do nothing if c is None and will return a None. Otherwise, it give you a Some(True) if, for example, close() returns a True when it succeeds. If close() had no return value, then mapping will return a Some(()) which has the type Option[Unit].