【发布时间】:2020-06-21 09:43:45
【问题描述】:
我正在使用 Scala Cats 开发一个小程序。在尝试将EitherT 与State 一起使用并用于理解时,我遇到了很多类型错误。例如:
import cats.data.{EitherT, State}
import cats.data.State.get
object Test {
type IntState[T] = State[Int, T]
type IntStateEither[T] = EitherT[IntState, String, T]
val test: IntStateEither[Unit] = for {
isValid <- EitherT.right(get.map((it: Int) => it % 2 == 0))
_ <- if (!isValid) EitherT.leftT("invalid number") else EitherT.rightT(()) // *
} yield ()
}
这给了我:
(...) Test.scala:12: type mismatch;
found : cats.data.EitherT[[A(in value <local Id>)]A(in value <local Id>),_1,Unit] where type _1 <: String
required: cats.data.EitherT[[A(in class IndexedStateT)]cats.data.IndexedStateT[cats.Eval,Int,Int,A(in class IndexedStateT)],String,Unit]
one error found
如果我注释掉上面标记为 (*) 的行,此代码将编译。我想我正确地遵循了“从A 或B 到EitherT[F, A, B]”下的说明on the Cats website,但是我需要提供更多类型提示吗?如果是,我不确定在哪里可以添加它们。
任何指针都非常感谢!
我正在使用 Cats 2.0.0 和 Scala 2.13.2。
【问题讨论】:
标签: scala scala-cats