【问题标题】:Scala type system, cannot find common ancestor inlineScala类型系统,找不到共同的祖先内联
【发布时间】:2019-10-07 08:21:37
【问题描述】:

我在一个重度类型系统上,其中一些泛型方法声明为def execute]C <: A#C](cmd: C):EitherT[Future, Fail, Seq[A#E]](其中A 是类的泛型类型。

这很好用。但是在我的测试中,当我模拟这些调用时,我必须明确键入 FailA#E 的超类型,否则我的代码无法编译。

// Event is the base type of Receiver#E
val event:Event = SubOfEvent()
handler.execute(any[SubOfCommand]) returns Seq(event).asRightT[Future, Fail]

val fail:Fail = SubOfFail()
handler.execute(any[SubOfCommand]) returns fail.asLeftT[Future, Seq[Receiver#E]]

如果我内联 eventfail 的声明,我有一个类型不匹配

  found   : cats.data.EitherT[scala.concurrent.Future,SubOfFail,scala.collection.immutable.Seq[SubOfEvent]]
  required: cats.data.EitherT[scala.concurrent.Future,Fail,scala.collection.immutable.Seq[Receiver#E]]
     (which expands to)  cats.data.EitherT[scala.concurrent.Future,Fail,scala.collection.immutable.Seq[Event]]
 Note: SubOfFail <: Fail, but class EitherT is invariant in type A.
 You may wish to define A as +A instead. (SLS 4.5)
     handler.execute(any[SubOfCommand]) returns SubOfFail().asLeftT[Future,
                                                                   ^

我理解关于EitherT 在类型A 中不变的消息。但我期待它能够将EitherT[F, SubOfA, B] 翻译为EitherT[F, SubOfA.asInstanceOf[A], B]

有人可以帮我揭示我推理中的缺陷吗?

谢谢

【问题讨论】:

    标签: scala scala-cats mockito-scala


    【解决方案1】:

    但我希望它能够将EitherT[F, SubOfA, B] 翻译为EitherT[F, SubOfA.asInstanceOf[A], B]

    不变意味着不可能以这种方式“翻译”:EitherT[F, SubOfA, B] 根本不是EitherT[F, A, B]

    现在,一个单独的问题是为什么fail 的类型没有被推断为Fail,尽管整个fail.asLeftT[Future, Seq[Receiver#E]] 的预期类型。答案是 Scala 类型推断不能那样工作。输入expression.method(...)时,会先输入expression,不能使用预期的返回类型method

    你仍然可以内联写它们,但你需要类型归属:

    (SubOfFail(): Fail).asLeftT[Future, Seq[Receiver#E]]
    

    如果是Seq,显式类型参数也可以:

    Seq[Event](SubOfEvent()).asRightT[Future, Fail]
    

    【讨论】:

    • 不知道表达式是先键入的,没有考虑方法的返回类型。但这是有道理的。感谢您的快速答复。
    • 基本上,如果不输入 expression,编译器将不知道要使用哪个 method 以及它的签名是什么(或签名,如果它被重载)。
    猜你喜欢
    • 2018-07-18
    • 1970-01-01
    • 2020-02-05
    • 2011-09-04
    • 1970-01-01
    • 2021-09-05
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多