使用 Cats,有没有更好/更惯用的方法来做到这一点?
class Foo
class Bar extends Foo
val eithertBar = EitherT.apply(SomeMonad(Right[Whatever, Bar](new Bar)))
val eithertFoo = EitherT[SomeMonad, Whatever, Foo].apply(eithertBar.value)
提取值并重新应用它感觉有点奇怪。谢谢。
最佳答案
是的,对于任何仿函数 F
Cats 提供了一个 widen
语法方法,可以完成您所请求的操作。因此,如果您有这个(为了举例,使用 Eval
作为 F
):
class Foo
class Bar extends Foo
import cats.Eval, cats.data.EitherT, cats.syntax.functor._
val eithertBar = EitherT[Eval, String, Bar](Eval.now(Right(new Bar)))
你可以这样写:
scala> eithertBar.widen[Foo]
res0: cats.data.EitherT[cats.Eval,String,Foo] = EitherT(Now(Right(Bar@5ab3a323)))
请注意,如果 F
是标准库类型构造函数(例如 Option
),或其他没有 Functor< 的类型构造函数
实例在其伴生对象中,您必须确保导入或以其他方式为其提供一个 Functor
才能使其正常工作。
关于scala - 如何向上转换 monad 变压器类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43310473/