小编and*_*tov的帖子

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

前段时间我开始使用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].

scala scala-cats

4
推荐指数
1
解决办法
396
查看次数

标签 统计

scala ×1

scala-cats ×1