Reputation: 13395
Is there a way to instantiate the value of map
lazy?
For example
class MapTest {
@Lazy(soft = true) HashMap<String, List<String>> map
}
Doing like this I can use this call and get null
without recieving NullPointerException
new MapTest().map.key1
However attempt to call
map.key1.remove(1)
will lead to NullPointerException
due the value
being null
. (it would be fine if it threw IndexOutOfBounds
exception)
Is there a way to instantiate the list
value of the map?
Upvotes: 0
Views: 1828
Reputation: 11022
try map.withDefault
:
def map = [:].withDefault { [] }
assert map.key1.isEmpty()
Some explanation :
withDefault
is a groovy method on a map wich take a closure. this closure is call every time a key is requested to initialize the value if it doesn't exist. this closure take one parameter (the key) and should the valuesee others examples here
Upvotes: 5