I'm working on a Scala project and Wartremover shows an error about Option#get
usage in my code:
Option#get is disabled - use Option#fold instead
While I do understand how get
should often be avoided, I think there are cases where it's reasonable to use it, like my current one: First, I create an answer item (in the database), then I want to return the freshly created answer by reading it from there.
def create(answer: Answer): Future[Answer] = {
writeToDb(answer) // returns Future[Long]
.flatMap(
readFromDb(_) // returns Future[Option[Answer]]
.map(_.get) // Wartremover complains here
)
}
My understanding is that get
should generally be avoided because it breaks control flow in case of None
, as an exception is thrown.
However, I expect my Option
here to always contain an answer, as I just created it.
If it's not there, there's likely a bug in my code or an issue with the database.
In such a case it would be unreasonable to fall back to a default value or null
. I'd much rather throw an exception or directly map to a failing future.
An alternative to get
is explicitly matching agains the option:
def create(answer: Answer): Future[Answer] = {
writeToDb(answer) // returns Future[Long]
.flatMap(
readFromDb(_) // returns Future[Option[Answer]]
.flatMap {
case Some(answer) => Future.successful(answer)
case None => Future.failed(
new IllegalStateException("Failed to load answer after creation"))
}
)
}
But this is way more verbose while achieving almost the same as a simple _.get
.
Am I missing something here? Or is this just a false positive from Wartremover?
answer
as context, rather than a general exception of "get on an emptyOption[Answer]
"