2017-04-09 53 views
2

使用猫,有没有更好/更习惯的方式来做到这一点?如何上传monad变压器类型?

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) 

提取的值,并重新施加感觉有点奇怪。谢谢。

回答

4

是的,对于任何函子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([email protected]))) 

注意,如果F是一个标准库类型构造(例如如Option),或其伴侣对象中没有Functor实例的某种其他类型的构造函数,则必须确保为其导入或以其他方式提供Functor才能使其工作。