Vitaliy Borisok
Vitaliy Borisok

Reputation: 861

Groovy skips JsonNode objects on checking for null even if they not null

Why Groovy skips this if statement?

public static void main(String[] args) {
    JsonNode jsonNode = JsonNodeFactory.instance.objectNode()
    if (jsonNode) {
        println 'It works' //doesn't print it
    }
}

Explicit checking for null works well:

public static void main(String[] args) {
    JsonNode jsonNode = JsonNodeFactory.instance.objectNode()
    if (jsonNode != null) {
        println 'It works' //works well
    }
}

Imports:

import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.JsonNodeFactory
import com.fasterxml.jackson.databind.node.ObjectNode

Also if I use breakpoints in Intellij it works.

Upvotes: 1

Views: 615

Answers (1)

Vitaliy Borisok
Vitaliy Borisok

Reputation: 861

It depends on Groovy Object#asBoolean. By default it returns false if object is null.

asBoolean()

Coerce an object instance to a boolean value. An object is coerced to true if it's not null, to false if it is null.

Groovy tries to cast object to boolean with asBoolean() when there is such check. This example shows that:

public static void main(String[] args) {
    AsBoolFalse asBoolFalse = new AsBoolFalse()
    if (asBoolFalse) {
        println 'AsBoolFalse doesn\'t work' //doesn't print it
    }

    AsBoolTrue asBoolTrue = new AsBoolTrue()
    if (asBoolTrue) {
        println 'AsBoolTrue works' //works well
    }
}

static class AsBoolFalse {
    public boolean asBoolean() {
        return false
    }
}

static class AsBoolTrue {
    public boolean asBoolean() {
        return true
    }
}

JsonNode overrides asBoolean() to return false, so we need explicit check for null.

Upvotes: 1

Related Questions