【问题标题】:Scala Cats Lifting values into Monad TransformersScala Cats 将值提升到 Monad Transformers
【发布时间】:2023-03-29 13:54:01
【问题描述】:

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


    【解决方案1】:

    错误是由于 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]))
    

    【讨论】:

      【解决方案2】:

      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.somenone[Int] 将被推断为 Option[Int]

      P.S:还有一个语法是通过cats.syntax.either._10.asRight[String]"Oops".asLeft[Int] 将被推断为Either[String, Int]

      【讨论】:

        猜你喜欢
        • 2019-05-19
        • 1970-01-01
        • 2017-01-04
        • 1970-01-01
        • 1970-01-01
        • 2018-06-09
        • 2019-03-16
        • 1970-01-01
        • 2018-08-27
        相关资源
        最近更新 更多