简体   繁体   中英

How to return different future types in scala for a method

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

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM