Sunday, 27 January 2019

Groovy: Assignment vs if statement


An assignment statement is not allowed as a top-level expression in if statement.

For example,
HelloWorld.groovy
if(a = 10){
 println "a is evaluated to true"
}else{
 println "a is evaluated to false"
}

As you see above snippet, you may think if statement evaluates to true (Since non-zero numbers are considered as true in groovy), but Groovy do not allow top level assignment statements.

You can perform the trick like by embedding the expression in extra parenthesis.


HelloWorld.groovy
if((a = 10)){
 println "a is evaluated to true"
}else{
 println "a is evaluated to false"
}

Output
a is evaluated to true


Previous                                                 Next                                                 Home

No comments:

Post a Comment