当将 for 理解与 EitherT
链接时,编译器在将我的错误向上转换为它们的共同祖先类型时遇到问题。
我的代码中有以下类型定义:
sealed trait Error
object Error:
case object Error1 extends Error
case class Error2(someParams) extends Error
到目前为止一切顺利。然后我就有了暴露这些东西的特征:
trait SomeInterface[F[_]]:
def someMethod(params): F[Either[Error1.type, Type1]]
def otherMethod(params): F[Either[Error2, Type2]]
然后在我的逻辑中,我以这种方式链接它们:
for {
t1 <- EitherT(someMethod)
t2 <- EitherT(otherMethod)
yield t2
理论上这应该可行,但我收到以下错误:
Found: EitherT[F, Error2, Type2]
Expected: EitherT[F, Error1.type, Any]
我已经尝试更改我的接口(interface),以便它们返回通用类型,但是当我实现时,它在转换它时遇到了麻烦。
我还尝试在 EitherT
构造函数中传递类型参数,但结果相同。
最佳答案
说实话,我不是一位出色的 FP 专家,所以我不确定我的解决方案是否是“干净的”解决方案,但每当我遇到此类问题时,我都会通过导入 cats.syntax.bifunctor.*
并在 EitherT
上调用 leftWiden[Error]
。
关于scala - EitherT 没有正确向上转换为共同特征父类(super class)型 (Scala 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76781190/