Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created January 8, 2016 16:42
Show Gist options
  • Select an option

  • Save bdkosher/acb703b0825fdbea2d6d to your computer and use it in GitHub Desktop.

Select an option

Save bdkosher/acb703b0825fdbea2d6d to your computer and use it in GitHub Desktop.
Potential Groovy Puzzler
/*
* Groovy has a controversial feature to call a single-arg method w/ null when no arg is passed.
* Equally surprising, if the first arg is an array, Groovy auto-passes an empty array instead
*
* Groovy has a useful feature called multiassignment. It's innocuous looking but not very forgiving;
* if used on a null or empty array, it will throw NPE and IndexOutOfBoundsExceptions respectively
*/
String m1(String arg) {
def a = arg
"$a"
}
String m2(String arg) {
def (a) = arg
"$a"
}
assert m1() == 'null' // true
assert m2() == 'null' /* fails: throws NPE: parens interpreted as multi-assignment, Groovy
attempts to call getAt() on the null argument */
/*
* What happens when we have an array/varargs as the first argument?
*/
String m3(String... args) {
def a = args
"$a"
}
String m4(String... args) {
def (a) = args
"$a"
}
assert m2() == 'null' // false: returns '[]' -- default no-arg passed value for array param
assert m3() == 'null' /* fails: throws ArrayIndexOutofBoundsException:
the use of parens attempts to multiassign the first
element of the array to a, and since the array is
empty, the indexing attempt produces a runtime error */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment