简体   繁体   English

如何在scala中为方法返回不同的未来类型

[英]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.嗨,我是 Scala 的新手,我被困在一个地方,正如 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 ?想想你的用户,应该如何他/她使用的结果saveVariabl如果它可以SomClassUnit You have to make explicit that behavior, and for that reason Either[L, R] exists.您必须明确该行为,因此存在Either[L, R]

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.此外,由于UnitLeft基本上没有意义,请考虑使用Option[T]作为@ale64bit 建议。

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] . Future.sucessful(())具有Future[Unit]类型(因为()具有类型Unit ),它与返回类型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.您没有提供SomeClass ,因此您需要返回Future.successful(new SomeClass())或类似的东西,它实际上具有预期的类型。

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) .如果您想返回有时丢失的值,请考虑返回Future[Option[SomeClass]]并且在 else 分支中您可以返回Future.successful(None) However, you will need to wrap the return value with Some() for the other case.但是,对于另一种情况,您需要使用Some()包装返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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