Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-8870

Spread-dot operator on list of lists

    XMLWordPrintableJSON

Details

    • Documentation
    • Status: Closed
    • Minor
    • Resolution: Fixed
    • None
    • 3.0.0-alpha-4, 2.5.4
    • None
    • None

    Description

      I'm not sure if this is intended, but I ran into some nice/useful behavior of the spread-dot operator when applying to a list of lists. I was trying to use collectMany and found that I would need to do an inner collectMany or switch to inject. But it turns out spread-dot and flatten handled the situation very nicely.

      Could you please add a note on this to the documentation (section 1.2.8 – other operators)? I don't think it is common knowledge that spread-dot does not always gather up results in a flat list.

      class Foo {
        String thing
      }
      class Bar {
        List<Foo> foos
      }
      class Baz {
        List<Bar> bars
      }
      
      List<Foo> f = [new Foo(thing:'1'), new Foo(thing:'2')]
      assert f*.thing == ['1','2']
      
      List<Bar> b = [new Bar(foos:f), new Bar(foos:f)]
      assert b*.foos*.thing == [['1','2'], ['1','2']]
      assert b*.foos*.thing.flatten()​ == ['1','2','1','2']
      
      // this was my use case:
      List<Baz> z = [new Baz(bars:b), new Baz(bars:b)]
      ​assert z*.bars*.foos == [[f, f], [f, f]] // each f is a list of 2 Foos
      assert z*.bars*.foos*.thing == [[['1','2'], ['1','2']], [['1','2'], ['1','2']]]
      assert z*.bars*.foos*.thing.flatten()​ == ['1','2','1','2','1','2','1','2'] // for the win!
      
      // in this case I could have also written it without the stars:
      assert z.bars.foos.thing.flatten()​ == ['1','2','1','2','1','2','1','2']
      

      Attachments

        Activity

          People

            paulk Paul King
            emilles Eric Milles
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: