在 Scala 中进行模式匹配时类型推断不正确

Incorrect type inference while pattern matching in Scala

在下面的 ADT 中,为什么 Foo 被错误地推断为它的类型参数 S

sealed trait Sum[-S, +A]

case class Foo[S]() extends Sum[S, S]

def execute[S, A](mqtt: Sum[S, A], s: S): A =
  mqtt match {
    // S and A should be the same for Foo
    case Foo() => s // should compile but returns an error.
  }  

Link 在 scastie https://scastie.scala-lang.org/xD4RqwKYRW20dy4K0GHEDg

您正在使用两个不同类型的参数 SA 调用方法 execute,编译器没有证据表明它们相同。

因此,当您尝试 return 类型为 S 的对象时,当方法签名需要 A 时,您会收到错误消息。这与ADT无关。

如果您向编译器提供有关类型参数的更多详细信息,则可以使其正常工作。 比如这个def execute[A, S<:A]

我能够使用类型化模式匹配而不是构造函数模式匹配来解决问题


sealed trait Sum[-S, +A]

case class Foo[S]() extends Sum[S, S]

def execute[S, A](mqtt: Sum[S, A], s: S): A =
  mqtt match {
      case m : Foo[S] => s
  }