Scala Cats将值提升为Monad变形金刚

问题描述 投票:2回答:2

我正在阅读关于将值提升到Monad变形金刚的this文档。

基于此,我编写了以下代码

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
2个回答
3
投票

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

1
投票

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]

© www.soinside.com 2019 - 2024. All rights reserved.