How to return different future types in scala for a method

1888 views scala
9

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 ??

answered question
Add a Comment

2 Answers

11

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.

posted this
12

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)

posted this

Please login first before posting an answer.