OK9999 OK9999 - 3 months ago 36
Groovy Question

Groovy syntax explaination

I came across the below function,

def some_name = {a, b, c -> a==c?bumpUp(b):b}

although i can understand that this function is some sort of short hand (can't recall or figure out the long form). It taking the 3 arguments, comparing for equally of a & c, if equal calling another function


So questions are:

1. is my assumption on the logic right?

2. what is the long way of writing this and what is it called?

3. what is the
doing in the


The Ternary operator which involves both a ? and a : , is a short and clean way to use an equivalent to an if statement. Reduction of the code verbosity hence makes it more readable.

For example:

String result = (1==1) ? 'equals' : 'not equals'

Lets explain the line above:

If the condition (1==1) is true, then the result assignment will be 'equals', else the result assignment will be 'not equals'.

The long way you probably familiar with is as follows:

String result = ""
if(1==1) {
    result = 'equals'
} else {
    result = 'not equals'

In order to answer your 3 questions:

  1. Your assumption on the logic is right. :-)
  2. The long way of writing it is described in the question 2 section.
  3. The :b relates to the else section. the ':' is just a separator for the b variable. In case the if (a==c) is false then go to the section code after the ':' and in that particular case it is b.

question 2 section:

    some_name = bumpUp(b)
} else {
    some_name = b