Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ==~ and != in Groovy?

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.'
}
like image 540
kschmit90 Avatar asked Mar 03 '15 20:03

kschmit90


People also ask

What does != Mean in Groovy?

!== 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.

Why we use def in Groovy?

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.

Is 0 false in Groovy?

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.


2 Answers

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

like image 123
Marvin Avatar answered Sep 19 '22 13:09

Marvin


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:

  1. "1234" ==~ /\d+/ -> evaluates to true
  2. "nonumbers" ==~ /\d+/ -> evaluates to false
like image 39
mkobit Avatar answered Sep 20 '22 13:09

mkobit