首页 > 解决方案 > Incorrect type inference while pattern matching in Scala

问题描述

In the following ADT, why is Foo incorrectly inferred for it's type parameter 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 on scastie https://scastie.scala-lang.org/xD4RqwKYRW20dy4K0GHEDg enter image description here

标签: scalafunctional-programmingpattern-matchingalgebraic-data-types

解决方案


You are calling method execute with two different type parameters S and A and compiler has no evidence they are same.

So when you try to return object of type S when method signature requires A you get an error. This has nothing to do with ADT.

You can make it work if you give compiler some more details about type parameters. Such as this def execute[A, S<:A]


推荐阅读