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?