lapots
lapots

Reputation: 13395

lazy instantiation of the map value

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

Answers (1)

J&#233;r&#233;mie B
J&#233;r&#233;mie B

Reputation: 11022

try map.withDefault :

def map = [:].withDefault { [] }
assert map.key1.isEmpty()

Some explanation :

  • [:] is the groovy way to instantiate an empty hash map
  • 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 value
  • [] is the groovy way to create an empty list - { [] } is a closure wich return an empty list for every key

see others examples here

Upvotes: 5

Related Questions