conditional-operatorelvis-operator

Using elvis/ternary operator as an argument to a function


Let's say I have this block of code in Groovy:

String x
String y = "hello"

def func(String str){
   println(str)
}

func(x ?: y)

Is there anything wrong with using Elvis operator as an argument to a function like I did above? I tested it and it works as expected, however, I've never seen Elvis operator to be passed to a function like that.

Thanks in advance!


Solution

  • I've never seen Elvis operator to be passed to a function

    Contrary to what your intuition is telling you, you're not seeing it here either. The operator isn't passed to the function. The result of the expression is.

    This expression evaluates to a result:

    x ?: y
    

    The result of this expression is a String value. That String value is passed to the function. It doesn't matter to the function how that String value was produced before it was passed to the function.