Reputation: 379
Hi I am new to scala and I am stuck in a place as explained belore.
def saveVariable(mappings: Seq):Future[SomeClass] =
if(mappings.nonEmpty) {
// a method is called that return a Future[SomeClass]
} else Future.sucessfull(()) // need to return a empty future or
In the else part I do not want to do anything. I want to do an action only if mappings is nonEmpty.
But if I do something like this, obviously compiler complain that return type does not match for else part.
How can I solve this problem ??
Upvotes: 0
Views: 201
Reputation: 22850
Think about your user, how should he / she use the result of saveVariabl
if it may be either SomClass
or Unit
? You have to make explicit that behavior, and for that reason Either[L, R]
exists.
def foo[T](mappings: Seq[T]): Future[SomeClass] =
???
def saveVariable[T](mappings: Seq[T]): Future[Either[Unit, SomeClass]] =
if(mappings.nonEmpty)
foo(mappings).map(sc => Right(sc))
else
Future.sucessfull(Left(()))
Also, since a Left of just Unit
is basically meaningless, consider using Option[T]
as @ale64bit suggested.
def saveVariable[T](mappings: Seq[T]): Future[Option[SomeClass]] =
if(mappings.nonEmpty)
foo(mappings).map(sc => Some(sc))
else
Future.sucessfull(None)
Upvotes: 2
Reputation: 6242
Future.sucessful(())
has type Future[Unit]
(because ()
has type Unit
), which doesn't match the return type Future[SomeClass]
. You are not providing SomeClass
, so you would need to return Future.successful(new SomeClass())
or something like that, that actually has the expected type.
If you want to return a value that is sometimes missing, consider returning Future[Option[SomeClass]]
instead and in the else branch you can return Future.successful(None)
. However, you will need to wrap the return value with Some()
for the other case.
Upvotes: 0