Scala Cats 将值提升到 Monad Transformers 中

标签 scala scala-cats

我正在阅读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/

相关文章:

functional-programming - F# 中是否有类似于 scalaz、cats 和 arrow (Kotlin) 的库?

arrays - 为什么 Scalaz 中没有 Array 的 Functor 实例

scala - 设计从 channel 读取的引用透明函数

scala - 在哪里使用 `ApplicativeError` 而不是 `Either` ?

scala - 对Cats Effect IO进行认真评估并忘记行为

scala - 为 fs2.Stream 的所有元素同时安排计算

scala - 如何解决在逆变位置使用协变类型参数的问题

function - 这两种结构之间的根本区别是什么?

scala - Finagle + 节俭 : Count method invocations

scala - Scala 函数的 IntelliJ 错误 : "cannot resolve reference format with such signature"