【发布时间】:2011-10-25 17:10:24
【问题描述】:
我正在编写基于树的表达式求值器,但在类型擦除方面遇到了一些麻烦。
树看起来像
sealed abstract class Node[+T]
case class Var[+T](name:String) extends Node[T]
/* SNIP */
评估者是
def eval[T](node:Node[T], context:Map[String, Any]):Option[T] = node match {
case Var(name) => context.get(name) match {
case Some(value:T) => Some(value)
case _ => None
}
/* SNIP */
}
代码可以编译,但对Var 节点的类型检查不起作用。所以这个测试失败了:
class ContextEvaluatorTest extends FunSuite with ShouldMatchers {
test("evaluation with type mismatch") {
ContextEvaluator.eval(Var[Int]("a"), Map("a" -> "not int")) should equal (None)
}
}
错误信息是
org.scalatest.TestFailedException: Some(not int) did not equal None
情况看起来像是清单的用例,但我无法正确添加它们。
【问题讨论】:
标签: generics scala pattern-matching