Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 495
tusharmath Avatar asked Feb 16 '26 20:02

tusharmath


2 Answers

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]

like image 60
tentacle Avatar answered Feb 19 '26 05:02

tentacle


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
  }

like image 24
tusharmath Avatar answered Feb 19 '26 06:02

tusharmath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!