【问题标题】:scala type mismatch found Future[A] expected Future[B]发现 scala 类型不匹配 Future[A] 预期 Future[B]
【发布时间】:2020-10-17 08:27:00
【问题描述】:

对 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 请求返回结果,将其映射到 Config。在我的 andThen 子句中将其转换为 Contract 类型并返回。

但我得到一个类型不匹配

[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]

【问题讨论】:

    标签: scala future


    【解决方案1】:

    Future#andThen 旨在执行副作用而不改变未来的价值。要转换 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 对应于Futures。

    【讨论】:

    • 哦,有趣,好吧,让我试试。谢谢
    • 谢谢你的回答,所以如果以后发生错误,map不会被调用,它会去恢复吗?
    • @Pita 是的,成功的映射也是其他错误单子的常见模式,例如 Either、Option、Try 等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 2018-06-29
    相关资源
    最近更新 更多