-1

All,

I am having an issue here with Groovy. Specifically I would like to use the inject method on a current list that I have. I need this list to be Immutable and built per element. Here is what my list looks like:

def initialList = [ "A", "B", "C" ]

I want to be able to to use an inject statement to add/build to this list on the fly and assign it to a variable. The desired code should look something like the following:

def result = initialList.inject(){ initialList + valueOfNextLetter() }

Obviously the semantics of this inject are escaping me. I have a function that will return the next value, but I cannot seem to get the list added element by element. What is the ideal result is code that will take the current state of initialList, return the next value, and then inject the processed result at the end of initialList. I cannot seem to understand Groovy inject. Please help. Any comments are helpful.

DaGr8Gatzby
  • 21
  • 2
  • 7
  • 1
    Which part of [this answer](http://stackoverflow.com/a/19287092/2051952) was unable to convey the usage of `inject`? I would be happy to clear the gray area. :) Instead of posting a duplicate question you can comment on [your previous question](http://stackoverflow.com/questions/19286182/combining-two-immutable-lists-with-inject). – dmahapatro Oct 11 '13 at 00:49

1 Answers1

0

If what you want to accomplish is

...code that will take the current state of initialList, return the next value, and then inject the processed result at the end of initialList.

I think using Collection#plus(Object) may be what you want rather than inject.

def initialList = ['A', 'B', 'C']

def valueOfNextLetter = {
    'D'
}

def newList = initialList + valueOfNextLetter()

assert ['A','B','C','D'] == newList
assert ['A','B','C'] == initialList
John Wagenleitner
  • 10,967
  • 1
  • 40
  • 39