【发布时间】:2015-07-15 15:38:32
【问题描述】:
这不输入:
sealed trait BinOp[-InA, -InB, +Out]
case object Add extends BinOp[Int, Int, Int]
sealed trait Expression[+A]
final case class IntegerAtom(value: Int) extends Expression[Int]
final case class BinaryExp[-A, -B, +C](op: BinOp[A, B, C], lhs: Expression[A], rhs: Expression[B]) extends Expression[C]
def optimizeStep[A](x: Expression[A]): Expression[A] = x match {
case BinaryExp(Add, IntegerAtom(a), IntegerAtom(b)) => IntegerAtom(a + b)
}
最直接的就是在模式匹配中使用case对象:
[error] (...) pattern type is incompatible with expected type;
[error] found : minimumexample.Add.type
[error] required: minimumexample.BinOp[Any,Any,A]
看来这个可以通过引入眼出血来解决:
val AddOp = Add
然后:
case BinaryExp(AddOp, IntegerAtom(a), IntegerAtom(b)) => IntegerAtom(a + b)
然后:
[error] (...) type mismatch;
[error] found : minimumexample.IntegerAtom
[error] required: minimumexample.Expression[A]
[error] case BinaryExp(AddOp, IntegerAtom(a), IntegerAtom(b)) => IntegerAtom(a + b)
[error] ^
我想尽可能安全地解决这个问题,而不是求助于.asInstanceOf[]。想法?
【问题讨论】:
-
这是一个最小(非)工作示例。编译器不理解
A在模式匹配后变成Int。 -
我的意思是,我在将代码粘贴到 REPL 时遇到的错误与您遇到的错误有很大不同。方差错误导致您询问的后续错误。
标签: scala pattern-matching type-inference