sakeesh
sakeesh

Reputation: 1049

Cannot invoke method multiply() on null object groovy

Consider below code

task circle {
doLast {
    float r = Float.parseFloat(project.properties["radius"])
    println (22/7)*(r ** 2)
}
}
task square {
     doLast {
       float s = Float.parseFloat(project.properties["side"])
       println s*s
     }
}

This give error as Cannot invoke method multiply() on null object

If I change the above code as below then it goes fine

task circle {
doLast {
    float r = Float.parseFloat(project.properties["radius"])
    println 22/7*(r ** 2)
}
}
task square {
     doLast {
       float s = Float.parseFloat(project.properties["side"])
       println s*s
     }
}

What could be the reason?

Upvotes: 2

Views: 1910

Answers (1)

cfrick
cfrick

Reputation: 37063

The problem here is the missing parens for the actual println, that will lead to the following code being executed (println(22/7))*(r ** 2). The println is done first and its result (void) becomes null. And then it throws the error you are seeing. Your "not-throwing" example nudges the parser in the right direction.

Parens in groovy are "optional if unambiguous", which is quite a broad term. Granted, that this got better with the new parrot-parser, you will often see things like this blow up. Simple rule of thumb: just don't leave out the parens for calling functions unless you are dealing with a trivial term.

Upvotes: 4

Related Questions