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

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]
I was able to solve the problem using a typed pattern match instead of a constructor pattern match
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With