What is the difference between these?
Why use one over the other?
def variable = 5
if( variable ==~ 6 && variable != 6 ) {
return '==~ and != are not the same.'
} else {
return '==~ and != are the same.'
}
!== not identical (Since Groovy 3.0.0) Here are some examples of simple number comparisons using these operators: assert 1 + 2 == 3 assert 3 != 4 assert -2 < 3 assert 2 <= 2 assert 3 <= 4 assert 5 > 1 assert 5 >= -2.
The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language. Here, firstName will be a String, and listOfCountries will be an ArrayList. Here, multiply can return any type of object, depending on the parameters we pass to it.
That is why Groovy coerce 0 to false and any non-zero number to true . There are other coercions that Groovy mades for you, e.g. empty list coerces to false , empty string coerces to false etc.
In groovy, the ==~
operator (aka the "match" operator) is used for regular expression matching. !=
is just a plain old regular "not equals". So these are very different.
cf. http://groovy-lang.org/operators.html
In Java, !=
is “not equal to” and ~
is "bitwise NOT". You would actually be doing variable == ~6
.
In Groovy, the ==~
operator is "Regex match". Examples would be:
"1234" ==~ /\d+/
-> evaluates to true
"nonumbers" ==~ /\d+/
-> evaluates to false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With