I was looking for an answer on what |=
does in Groovy and although answers above are right on they did not help me understand a particular piece of code I was looking at.
In particular, when applied to a boolean variable "|=" will set it to TRUE the first time it encounters a truthy expression on the right side and will HOLD its TRUE value for all |= subsequent calls. Like a latch.
Here a simplified example of this:
groovy> boolean result
groovy> //------------
groovy> println result //<-- False by default
groovy> println result |= false
groovy> println result |= true //<-- set to True and latched on to it
groovy> println result |= false
Output:
false
false
true
true
Edit: Why is this useful?
Consider a situation where you want to know if anything has changed on a variety of objects and if so notify some one of the changes. So, you would setup a hasChanges
boolean and set it to |= diff (a,b)
and then |= dif(b,c)
etc.
Here is a brief example:
groovy> boolean hasChanges, a, b, c, d
groovy> diff = {x,y -> x!=y}
groovy> hasChanges |= diff(a,b)
groovy> hasChanges |= diff(b,c)
groovy> hasChanges |= diff(true,false)
groovy> hasChanges |= diff(c,d)
groovy> hasChanges
Result: true