我正在为自定义无类型表达式创建一个新的抽象语法树,我想在其上重新定义 == 运算符,如下所示:
trait Expression {
def ==(other: Expression): Expression = Equality(this, other)
def !=(other: Expression): Expression = Inequality(this, other)
}
case class Equality(e1: Expression, e2: Expression) extends Expression
case class Inequality(e1: Expression, e2: Expression) extends Expression
case class Integer(e: Int) extends Expression
case class Boolean(e: Boolean) extends Expression
我现在遇到的唯一问题是测试这种表达式的无效性。例如,当我写这个时:
val formula: Expression = someFunctionReturingAnExpression
if(formula != null) {
... use the formula.
}
它抛出一个java.lang.NullPointerException
,因为它正在将该方法!=
应用于formula
.
关于如何具有可表达性!=
以及空检查的任何好主意?