groovykoans icon indicating copy to clipboard operation
groovykoans copied to clipboard

Tricky Solution for 'test05_ElvisAndSafeNavigation'

Open abelsromero opened this issue 10 years ago • 2 comments

I don't consider myself a Groovy expert but not a novice either and I found quite a tricky behauvior that may need some extra clarification in test05. I wrote the following solution, which may seem correct: message = 'Hello ' + userService.getLoggedInUser()?.getFirstName()?:'Anonymous' + '!' However, unless parenthesis are added as follows it does not work message = 'Hello ' + (userService.getLoggedInUser()?.getFirstName()?:'Anonymous') + '!'

Seeing why in one case it returns "Hello null" is easy, but understanding why on the other the result is "Hello Ronaldo" is not.

Seeing the missleading behauviour of elvis operator, ¿wouln'd it be nice to add a test for it, or some extra information?

Thanks

abelsromero avatar Aug 08 '14 16:08 abelsromero

Care to submit a pull request? :) On Aug 8, 2014 9:06 AM, "abelsromero" [email protected] wrote:

I don't consider myself a Groovy expert but not a novice either and I found quite a tricky behauvior that may need some extra clarification in test05. I wrote the following solution, which may seem correct: message = 'Hello ' + userService.getLoggedInUser()?.getFirstName()?:'Anonymous' + '!' However, unless parenthesis are added as follows it does not work message = 'Hello ' + (userService.getLoggedInUser()?.getFirstName()?:'Anonymous') + '!'

Seeing why in one case it returns "Hello null" is easy, but understanding why on the other the result is "Hello Ronaldo" is not.

Seeing the missleading behauviour of elvis operator, ¿wouln'd it be nice to add a test for it, or some extra information?

Thanks

— Reply to this email directly or view it on GitHub https://github.com/nadavc/groovykoans/issues/26.

nadavc avatar Aug 08 '14 21:08 nadavc

This is a very old issue but in order to avoid further confusion for a future reader: the problem is not a "misleading behauviour of the elvis operator". The need of parenthesis shows that the cause of such problem is the simple and old operators' precedence rule. + has a higher priority than ?: so, without parenthesis the expression is evaluated as follows: ( 'Hello ' + userService.getLoggedInUser()?.getFirstName() ) ?: ( 'Anonymous' + '!' ).

Update: IMHO there's no need for an extra test or anything similar because is a matter of CS 101 and not a language quirk. Nonetheless, a comment mentioning that + has a higher priority than ?: could be useful.

EPadronU avatar Mar 03 '16 04:03 EPadronU