The following code returns a Future
.
val findUserFuture: Future[Option[User]] = userRepo.findOne(userKeys)
Then I process the Future
findUserFuture.flatMap {....}
.recover{...}
I suppose that recover
will be called if flatMap
throws an Exception
. But what if findOne
returns null
? Is there a Scala
specific way to check that findUserFuture
is not null
? I can I suppose do if(findUserFuture != null)
but I am wondering is Scala
provides some different way to check null
s
There is a difference between the result of the Future
and the Future
itself, and between null
and None
.
null
is a hang-over from Java that is typically not used in Scala. The only way that the Future
itself could be null
is if findOne
returned null
, which is very unlikely. So testing the Future
itself is not going to be useful.
The result of the future is Option[User]
so the code inside the flatMap
will be give a value that is either Some(user)
or None
. You can use the standard Option
methods to test this value. Typically you would match
on the value or call map
to process the contents, if present. There are lots of stackoverflow answers that explain how to unpick an Option
value safely.
Note that the Option[User]
value could be null
but, again, this is very unlikely and would be an error in the library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With