【发布时间】:2016-08-01 20:38:12
【问题描述】:
所以,我是 Scala 的新手,来自 Java 背景,并且有大量的 scala 代码库可供学习。而且,我很迷茫,不胜感激。
我想重新安排以下功能。目前,该函数连续调用两个函数,然后返回结果。第一个函数返回一个布尔值,第二个函数返回一个用户。然而,实际上应该发生的是,只有在第一个函数返回 true 时才应该调用第二个函数。所以,在继续之前,我需要重新排列它以检查第一个函数的返回值。每次我重写它来执行此操作时,我都会收到编译错误或异常。它应该返回一个 Future[Option[User]] 并且第一个函数不返回一个用户。如果 FunctionA 失败,我只想返回 None,但因为它需要 Future[Option[X]]],所以很不高兴。所以,下面是函数:
private def profileForCredentials(userId: String, password: String)(implicit ec: ExecutionContext): Future[Option[User]] =
{
val credentials: Throwable \/ Boolean = {
try {
FunctionA(userId, password).right[Throwable]
}
catch {
case npe: NullPointerException =>
npe.left[Boolean]
}
}
//This function doesn't need to be called unless credentials=true
FunctionB(id, userId).map {
case maybeUser@Some(user) =>
credentials match {
case \/-(x) if x =>
user.some
case _ =>
None
}
case None =>
None
}
}
【问题讨论】:
-
Future在哪里? -
尝试返回
Future { None }而不是None -
@Jean Logeart FunctionB 可能会返回 Future。
-
我们需要
FunctionA和FunctionB的返回类型来帮助你
标签: scala