I am creating a new Abstract Syntax Tree for custom untyped expressions, and I wanted to redefine the == operator on it, like that:
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
The only problem I now encounter is to test the nullity of such expression.
For example, when I write this :
val formula: Expression = someFunctionReturingAnExpression
if(formula != null) {
... use the formula.
}
it throws a java.lang.NullPointerException, because it is applying the method != to formula.
Any good idea on how to have the expressibility of != and also the null check ?
You are overloading the
==,!=operators there. The code you showed doesn’t really compile for me since it cannot cast Expression to Boolean in the if clause. So you could use a downcast on the null there so that the compiler uses the==operator fromAny:The above expression works for me.
You can also use the reference equality operator from
AnyRef:I also subscribe to ziggystar and Dylan’s comments – you should use a different operator name (
===, for example) and don’t usenull– useOptioninstead.