2017-04-09 35 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才能使其工作。