此代码编译错误:
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 ...
Run Code Online (Sandbox Code Playgroud)
从类型检查角度看,实现GADT的代码看起来非常相同,但编译时没有错误:
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
}
Run Code Online (Sandbox Code Playgroud)
在两种情况下,在模式匹配表达式中,我们知道i和b是Int和Boolean.为什么第一个例子编译失败而第二个例子成功?
| 归档时间: |
|
| 查看次数: |
236 次 |
| 最近记录: |