Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading