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

Have the elvis operator (?:) support the Optional type in Java 8

    Details

    • Type: New Feature
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 2.5.0-beta-1
    • Component/s: Compiler
    • Labels:

      Description

      With Java 8 and the rising popularity of Optional type in lieu of null management, it would be great if Groovy's elvis could handle Optional in the same way.

      Optional<String> string1 = Optional.of("foo")
      Optional<String> string2 = Optional.empty()
      
      assert "foo" == ( string1 ?: "bar" )
      assert "bar" == ( string2 ?: "bar" )
      
      

      Conversely, another option is to make elvis overloadable. ( something like orElse() ).

      That way, other Option/al types ( i.e. from Guava or FJ ) can have extension methods to support their use as well.

        Issue Links

          Activity

          Hide
          jwagenleitner John Wagenleitner added a comment -

          Thanks for improvement request. I think the for GROOVY-7611 addresses this issue.

          Show
          jwagenleitner John Wagenleitner added a comment - Thanks for improvement request. I think the for GROOVY-7611 addresses this issue.
          Hide
          paulk Paul King added a comment - - edited

          Marked as a breaking change for anyone relying on the old behavior.

          If you were working around the old behavior using the ternary operator, i.e.:

          def empty = Optional.empty()
          def foo = Optional.of('foo')
          def bar = Optional.of('bar')
          assert foo.isPresent() ? foo : bar == foo
          assert empty.isPresent() ? empty : bar == bar
          

          you can leave your code unchanged or change to the more compact elvis operator notation version:

          assert foo ?: bar == foo
          assert empty ?: bar == bar
          
          Show
          paulk Paul King added a comment - - edited Marked as a breaking change for anyone relying on the old behavior. If you were working around the old behavior using the ternary operator, i.e.: def empty = Optional.empty() def foo = Optional.of('foo') def bar = Optional.of('bar') assert foo.isPresent() ? foo : bar == foo assert empty.isPresent() ? empty : bar == bar you can leave your code unchanged or change to the more compact elvis operator notation version: assert foo ?: bar == foo assert empty ?: bar == bar

            People

            • Assignee:
              jwagenleitner John Wagenleitner
              Reporter:
              aadi.deshpande Aadi Deshpande
            • Votes:
              1 Vote for this issue
              Watchers:
              4 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved:

                Development