【问题标题】:Scala: Cats, OptionT[Future, T] and ApplicativeErrorScala:Cats、OptionT[Future, T] 和 ApplicativeError
【发布时间】:2018-02-24 04:01:26
【问题描述】:

前段时间我开始使用 Cats,发现 OptionT 在大多数情况下与 Future[Option[T]] 一起工作非常有用。但是我面临一个缺点,要使用AplicativeError,我需要定义类型别名type FutureOption[T] = OptionT[Future, X] 以匹配AplicativeError 所需的F[_],并将我的表达式类型明确指定为FutureOption[T]。

type FutureOption[T] = OptionT[Future, T] // definition to match F[_] kind

val x = OptionT.liftF(Future.failed(new Exception("error"))) : FutureOption[String] // need to specify type explicitly
x.recover {
  case NonFatal(e) => "fixed"
}

如果我删除表达式的类型定义和显式类型规范,recover 将不可用,因为 OptionT[Future, T] 不匹配 F[_],因此它无法隐式转换为 AplicativeErrorOps。

很遗憾,下面的示例不起作用,因为没有 recover 方法。

val x = OptionT.liftF(Future.failed(new Exception("error")))
x.recover {
  case NonFatal(e) => "fixed"
}

有没有办法避免这种样板代码?至少我想避免将表达式类型明确指定为FutureOption[T]。

【问题讨论】:

    标签: scala scala-cats


    【解决方案1】:

    除了其他答案,我建议您确保为您的构建启用了-Ypartial-unification。

    这是对partial unification of type constructors 的修复。您可以找到有关修复 here 的更详细说明。

    启用部分统一后,您在问题中提供的代码可以正常编译。请注意,如果您使用的是 IDE(例如 Intellij),您可能会得到“假阴性”(代码下划线表示不正确并且代码完成不起作用),但 scalac/sbt/gradle 会编译它就好了。

    【讨论】:

    • 非常感谢!它被禁用了。现在可以在没有显式类型的情况下正常编译。不幸的是,idea 将代码突出显示为不正确。
    • 不幸的是,IDEA 仍然不能正确支持部分统一。您可以前往youtrack.jetbrains.com/issue/SCL-11320 投票以将该问题列为更高优先级。
    【解决方案2】:

    是的,至少有两种方法可以处理类型归属。

    • 使用 lambdas 类型(这可能很吓人):

      val a: { type λ[A] = OptionT[Future, A] }#λ
      
    • 使用像kind-projector这样的编译器插件,示例用法:

      val a: Lambda[A => OptionT[Future, A]]
      

    但是如果你想打电话给Future的recover,你可以随时这样做:

    val x = OptionT.liftF(Future.failed(new Exception("error")))
    x.value.recover ...
    

    【讨论】:

    • 感谢您的建议!我阅读了有关 kind-projector 的信息,但我仍然不太清楚在这种情况下如何使用它。您能否提供一些更详细的示例。至于x.value.recover ...,我知道这个选项,但我更喜欢留在OptionT monad,因为我还有其他计算。
    • 如 kind-projector documentation 所述,如果您在构建中启用 kind-projector,则可以使用类型注释 OptionT[Future, ?] 和 λ[A => OptionT[Future, A]]。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多