发现 Scala 类型不匹配 Future[A] 预期 Future[B]

scala type mismatch found Future[A] expected Future[B]

对 scala 有点陌生,对这里的类型定义以及如何解决它有点困惑。

  private def getContract(organizationId: String, sc: SecurityContext): Future[Contract] = {
    val configRequest = ConfigsActor.ReadConfigRequest(CONFIG_KEY, Option(organizationId))(sc)
    (configActor ? configRequest).mapTo[Config] andThen {
      case Success(config) =>
        JsonUtil.extract[Contract](config.data)
      case otherwise =>
        log.warning("some unknown case has happened", otherwise)
    }
  }

我希望 akka 询问 return 结果,将其映射到配置。在我的 andThen 子句中将其转换为 Contract 类型并 return 它。

但我发现类型不匹配

[error] 
[error]  found   : scala.concurrent.Future[com.example.service.Config]
[error]  required: scala.concurrent.Future[com.example.service.Contract]
[error]     (configActor ? configRequest).mapTo[Config] andThen
[error]

Future#andThen 旨在执行副作用 而不会 转换未来的价值。要转换 Future 中的值,只需映射到 future

(configActor ? configRequest).mapTo[Config] map { config =>
  JsonUtil.extract[Contract](config.data)
} andThen { case Failure(e) => log.warning("some unknown case has happened", e) }

以下内容值得记住

someFuture
  .map     { value  => /* transform value */ }
  .recover { error  => /* transform error */ }
  .andThen {           /* execute side-effect */
    case Success(value) => logger.info("Successfully ...")
    case Failure(error) => logger.error("Failed to ...", error)
   }

您可以将 andThen 视为 tap Future 秒。