I am new to the Groovy language. Can someone please explain to me what this line of code means?
List<String> somevar = [].withDefault { }
Thanks.
As it says in the documentation :
Decorates a list allowing it to grow when called with a non-existent index value. When called with such values, the list is grown in size and a default value is placed in the list by calling a supplied init Closure
There's a good blog post about it here
It gives a default value for elements not yet in the list. For example
List<String> somevar = [].withDefault { }
println "Value at index 0 is "+somevar[0]; // gives null
println "Value at index 5 is "+somevar[5]; // gives null
List<String> somevarb = ['a'].withDefault { 'b' };
println "Value at index 0 is "+somevarb[0]; // gives a
println "Value at index 5 is "+somevarb[5]; // gives b
So when its empty like in your case it gives null . Read more here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.