Scala:Cats,OptionT [Future,T]和ApplicativeError

and*_*tov 4 scala scala-cats

前段时间我开始使用Cats,发现在大多数情况下使用它OptionT非常有用Future[Option[T]].但我面临一个缺点,使用AplicativeError我需要type FutureOption[T] = OptionT[Future, X]为匹配F[_]所需的类型定义类型别名,AplicativeError并明确指定我的表达式的类型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"
}
Run Code Online (Sandbox Code Playgroud)

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

不幸的是,下面的例子不起作用,因为没有recover方法.

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

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

Den*_*sca 5

除了其他答案,我建议您确保已-Ypartial-unification启用构建.

这是对类型构造函数的部分统一的修复.您可以在此处找到有关此修复程序的更详细说明.

启用部分统一后,您在问题中提供的代码编译得很好.请注意,如果您使用的是IDE(例如Intellij),您可能会收到"漏报"(代码加下划线标记错误且代码完成无效),但scalac/sbt/gradle会将其编译得很好.