Hello friends ,In this blog we learn how to create a groovy list with default value.
We can create and use withDefault() method to define the value of elements not yet in the list. We use a closure as a argument to this method which returns the default value. We can also access the index of element in the closure argumment.

  • Besides the withDefault() method we can use the withLazyDefault() which is just another name for the same functionality. If we request a value for an index that is greater or equal to the size of the list, the list will automatically grow up to the specified index. Any gaps are filled with the value null.
  • The following example script shows the results from using the withDefault() (withLazyDefault()) :
    def lazy = ['hello', 42].withDefault { 'default' }
    assert lazy[3] == 'default'
    assert lazy == ['hello', 42, null, 'default']
    
  • We can also use the withEagerDefault() method. If we use this method the gaps are filled with the result from the closure we pass to the method. So instead of the value null the return result from the closure is used.
  • The following example script shows the results from using the withEagerDefault():
    def eager = ['hello', 42].withEagerDefault { 'default' }
    assert eager[3] == 'default'
    assert eager == ['hello', 42, 'default', 'default']
    

Hope you love it 🙂