【问题标题】:How to assign a Future[Option[Int]] to a OptionT[Future, Int]如何将 Future[Option[Int]] 分配给 OptionT[Future, Int]
【发布时间】:2017-03-27 16:14:53
【问题描述】:

我创建了这个简单的 Monad 转换器

type FutureOptionInt = OptionT[Future, Int]

现在我可以通过以下方式轻松创建一个实例

1.pure[FutureOptionInt]

这很好。但我有另一个函数返回一个 Future[Option[Int]]。我无法将此函数的输出更改为 MT

所以我需要将返回类型分配给我的 MT。

我试过了

val y = Future(Option(1))
val x : FutureOptionInt = y

但我得到错误

cmd5.sc:1: type mismatch;
 found   : scala.concurrent.Future[Some[Int]]
 required: $sess.cmd3.FutureOption
    (which expands to)  cats.data.OptionT[scala.concurrent.Future,Int]
val x : FutureOption = y

所以问题是,如果你有一个 Future[Option[Int]],你如何将它分配给 OptionT[Future, Int]?

【问题讨论】:

    标签: scala scala-cats


    【解决方案1】:

    您可以使用隐式转换来做到这一点:

    implicit def toTransformer(future: Future[Option[Int]]) = OptionT(future)
    

    那么你的任务成功了。

    将选项中的内容抽象如下也可能对您有用,这样您就不必编写大量转换器:

    implicit def toTransformer[T](future: Future[Option[T]]) = OptionT(future)
    
    type FutureOpt[T] = OptionT[Future, T]
    
    val intOpt = Future(Option(1))
    val strOpt = Future(Option(""))
    
    val x : FutureOpt[Int] = intOpt
    val y : FutureOpt[String] = strOpt
    

    【讨论】:

      猜你喜欢
      • 2015-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 2019-08-12
      相关资源
      最近更新 更多