Applying the default groovy method parameter value when passing null

In Groovy, if I have:

def say(msg = 'Hello', name = 'world') { "$msg $name!" } 

And then call:

 say() // Hello world! say("hi") // Hi world! say(null) // null world! 

Why is the latter interpreted literally as null and does not apply the default value? Does this not override the default assignment of argument values ​​to a method? I get that passing null is different from not missing any length of the w / r / t argument.

My problem is that if I now have a method that takes a collection as an argument:

 def items(Set<String> items = []) { new HashSet<>(items) } 

This will NullPointerException if I call items(null) , but it works fine if I just say items() . In order for this to work correctly, I have to change the line as new HashSet<>(items ?: []) , Which, again, seems to be completely intended to have the default values ​​of the method arguments.

What am I missing here?

+5
source share
1 answer

In Groovy, default parameters generate overloaded methods. So this is:

 def items(Set<String> items = []) { new HashSet<>(items) } 

It will generate these two methods (I used javap to get these values):

 public java.lang.Object items(java.util.Set<java.lang.String>); public java.lang.Object items(); 

Therefore, when you call items(null) , you are actually passing some value, and the items(Set) method will be used.

You can also refer to this question about default options.

+6
source

Source: https://habr.com/ru/post/1238652/


All Articles