Search code examples
kotlininfix-notation

How do I properly check for null on nullable infix receivers?


I have a Kotlin infix function stubbed out thusly:

private fun statementMeetsConditions(policy: PolicyStatement, per: PolicyEnforcementRequest): Boolean {
    return policy.conditions areMetBy per.attributes
}

private infix fun JsonNode?.areMetBy(attributes: Map<String, String>): Boolean {
    if (this == null) return true //no conditions, so we pass

    TODO("Condition-based policies not implemented")
}

At runtime, policy.conditions is null.

enter image description here

I would have thought that (this == null) would evaluate to true, however I am triggering a runtime exception as the infix function hits the TODO.

These are both member functions on a class -- so I suspect that "this" is evaluating to the instance of the class (not null), rather than the JsonNode? I was expecting. How can I ensure that I'm referencing the JsonNode? instead of the class?


Solution

  • NullNode (jackson-databind-javadoc) is not null ;-) NullNode is actually its own type... So you may rather want to check against that type instead...

    Checking whether this is null works on infix functions the way you would expect, even if those extension functions are wrapped in a class.

    So to check whether your policy.conditions contains that NullNode you may rather change the condition to the following instead:

    if (this is NullNode) return true