Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how shall I check that a Future is not null

Tags:

scala

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 nulls

like image 245
Manu Chadha Avatar asked Dec 10 '22 03:12

Manu Chadha


1 Answers

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.

like image 154
Tim Avatar answered Dec 27 '22 10:12

Tim