Pawel Veselov
Pawel Veselov

Reputation: 4225

Groovy null safety with multiple assignment

Is there a way to "apply" null safety to a multiple assignment from a null? For example, this piece of code would obviously throw:

// verbosity is for clarity
def (a,b) = new HashMap<String, List<String>>().get("nothing")

but it would be neat to have it define a and b with null value.

So far I came up with

def (a,b) = new HashMap<String, List<String>>().get("nothing").with {[it?.get(0), it?.get(1)]}

But that's really ugly...

Upvotes: 0

Views: 255

Answers (1)

daggett
daggett

Reputation: 28564

This is the safe bet, if you have both missing keys and null values:

def (a,b) = new HashMap<String, List<String>>().get("nothing") ?: []

The next one is from Groovy, but modifies the underlying map (so only works for mutable maps and whether you are fine with modifying it) and it only gives the default for missing keys:

def (a,b) = new HashMap<String, List<String>>().get("nothing", [])

Similar (also from Groovy and also modifying the underlying map): withDefault. This option is great if you plan to pass the map around to other places, that would have to deal with the default all over again (also only defaults for missing keys):

def (a,b) = new HashMap<String, List<String>>().withDefault{[]}.get("nothing")

And the next one is from Java, but that also only falls back, if the key is missing:

def (a,b) = new HashMap<String, List<String>>().getOrDefault("nothing",[])

Upvotes: 2

Related Questions