我正在阅读this有关将值提升到 Monad Transformers 的文档。
基于此我编写了以下代码
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]
,它是选项[Int]
。但是 OptionT
完全需要 Option
,因此它不会编译。
你可以通过这样做来编译它
val z: FutureOption[Int] = OptionT(Future.successful(Option(10)))
或
val z: FutureOption[Int] = OptionT(Future.successful(Some(10): Option[Int]))
关于Scala Cats 将值提升到 Monad Transformers 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46453666/