[英]How to accept all types except Future in definition of method in Scala?
[英]How to return different future types in scala for a method
嗨,我是 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
在其他部分我不想做任何事情。 我只想在映射为非空时执行操作。
但是如果我做这样的事情,显然编译器会抱怨其他部分的返回类型不匹配。
我怎么解决这个问题 ??
想想你的用户,应该如何他/她使用的结果saveVariabl
如果它可以是SomClass
或Unit
? 您必须明确该行为,因此存在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(()))
此外,由于Unit
的Left基本上没有意义,请考虑使用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(())
具有Future[Unit]
类型(因为()
具有类型Unit
),它与返回类型Future[SomeClass]
不匹配。 您没有提供SomeClass
,因此您需要返回Future.successful(new SomeClass())
或类似的东西,它实际上具有预期的类型。
如果您想返回有时丢失的值,请考虑返回Future[Option[SomeClass]]
并且在 else 分支中您可以返回Future.successful(None)
。 但是,对于另一种情况,您需要使用Some()
包装返回值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.