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

Support flattening of Optionals in flatten/flattenMany

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Major
    • Resolution: Fixed
    • None
    • 5.0.0-alpha-1
    • None
    • None

    Description

      The functional idiom of map/collect then flatten is so common that we normally have a shorthand for combining them: flatMap, bind, collectMany.

      We have that for streams (piggybacking on Java) and collections but not optionals.

      var items = ["1", "2", "foo", "3", "bar"]
      
      var toInt1 = s -> s.number ? Stream.of(s.toInteger()) : Stream.empty()
      println items.stream().flatMap(toInt1).toList()
      
      var toInt2 = s -> s.number ? [s.toInteger()] : []
      println items.collectMany(toInt2)
      
      var toInt3 = s -> s.number ? Optional.of(s.toInteger()) : Optional.empty()
      println items.collect(toInt3).flatten{ it -> it.orElse([]) }
      println items.collect(toInt3).findResults{ it -> it.orElse(null) }
      println items.collect(toInt3).grep()*.get()
      

      This issue will explore options for adding that.

      Attachments

        Issue Links

          Activity

            People

              paulk Paul King
              paulk Paul King
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: