【问题标题】:EitherT + State type mismatchEitherT + 状态类型不匹配
【发布时间】:2020-06-21 09:43:45
【问题描述】:

我正在使用 Scala Cats 开发一个小程序。在尝试将EitherTState 一起使用并用于理解时,我遇到了很多类型错误。例如:

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

如果我注释掉上面标记为 (*) 的行,此代码将编译。我想我正确地遵循了“从ABEitherT[F, A, B]”下的说明on the Cats website,但是我需要提供更多类型提示吗?如果是,我不确定在哪里可以添加它们。

任何指针都非常感谢!

我正在使用 Cats 2.0.0 和 Scala 2.13.2。

【问题讨论】:

    标签: scala scala-cats


    【解决方案1】:

    问题似乎在于编译器无法推断出EitherT.leftTEitherT.rightT 的正确类型。
    您可以使用以下显式类型来修复这些错误:EitherT.rightT[IntState, String],或者如果您只需要一个 flatMap 调用,那么显式执行它似乎确实有效:

    val test: IntStateEither[Unit] =
      EitherT
        .right[String](State.get[Int].map(it => it % 2 == 0))
        .flatMap { isValid =>
          if (isValid) EitherT.rightT(())
          else EitherT.leftT("invalid number")
        }
    

    PS:bm4 是否有帮助可能值得检查

    【讨论】:

    • 行得通! bm4 并没有直接解决问题,但我还是把它添加到了我的构建中,看起来很有用。
    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    相关资源
    最近更新 更多