This code compiles with an error:
def f1[T](e: T): T = e match {
case i:Int => i
case b:Boolean => b
}
// type mismatch;
// found : i.type (with underlying type Int)
// required: T
// case i:Int => i ...
And this code implementing GADT looks pretty identical from type checking perspective, but compiles without error:
sealed trait Expr[T]
case class IntExpr(i: Int) extends Expr[Int]
case class BoolExpr(b: Boolean) extends Expr[Boolean]
def eval[T](e: Expr[T]): T = e match {
case IntExpr(i) => i
case BoolExpr(b) => b
}
In both cases inside pattern matching expression we know that i and b are Int and Boolean. Why compilation failed on first example and succeeded on the second one?
C++
preC++17
(with compile-time generics, but without compile-timeif
) I would have told that the method body is not correct for any typeT
, asT
is never bothInt
andBoolean
. – Emprisedef f1[T](e: T) = e
. If you want a solution, context would be helpful. Though perhaps you're just after a why – Tigress{ case i: Int => i+1; case b: Boolean => !b}
? :D – Yamadacase class Expr[T](v: T); def eval[T](e: Expr[T]): T = e match { case Expr(i: Int) => i; case Expr(b: Boolean) => b }
– Greff