[英]Scala Cats Lifting values into Monad Transformers
我读这个关于提升价值为Monad的变压器文档。
基于此,我编写了以下代码
import cats.data._
import cats.implicits._
type FutureOption[T] = OptionT[Future, T]
val x : FutureOption[Int] = 1.pure[FutureOption] // works
val y : FutureOption[Int] = OptionT.fromOption[Future](Some(10)) // works
val z : FutureOption[Int] = OptionT.liftF(Future.successful(10)) // works
现在,如果我尝试
val z = FutureOption[Int] = OptionT(Future.successful(Some(10)))
我得到一个错误
cmd4.sc:1: no type parameters for method apply: (value: F[Option[A]])cats.data.OptionT[F,A] in object OptionT exist so that it can be applied to arguments (scala.concurrent.Future[Some[Int]])
--- because ---
argument expression's type is not compatible with formal parameter type;
found : scala.concurrent.Future[Some[Int]]
required: ?F[Option[?A]]
val x : OptionT[Future, Int] = OptionT(Future.successful(Some(10)))
^
cmd4.sc:1: type mismatch;
found : scala.concurrent.Future[Some[Int]]
required: F[Option[A]]
val x : OptionT[Future, Int] = OptionT(Future.successful(Some(10)))
^
cmd4.sc:1: type mismatch;
found : cats.data.OptionT[F,A]
required: cats.data.OptionT[scala.concurrent.Future,Int]
val x : OptionT[Future, Int] = OptionT(Future.successful(Some(10)))
该错误是由于Scala类型推断引起的。
在没有显式Option
类型注释的情况下, Some(10)
的类型为Some[Int]
,它是Option[Int]
的子类型。 但是OptionT
期望Option
完全正确,因此它将无法编译。
您可以通过以下方式进行编译
val z: FutureOption[Int] = OptionT(Future.successful(Option(10)))
要么
val z: FutureOption[Int] = OptionT(Future.successful(Some(10): Option[Int]))
Gabrielle提供的解决方案的替代方案。 您可以使用cats lib提供的语法
import cats.syntax.option._
接着
val z: FutureOption[Int] = OptionT(Future.successful(10.some))
Or
val z: FutureOption[Int] = OptionT(Future.successful(none[Int]))
10.some
和none[Int]
将被推断为Option[Int]
PS:还有一个通过cats.syntax.either._
的语法10.asRight[String]
和"Oops".asLeft[Int]
将被推断为Either[String, Int]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.