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

[PARROT] Add "a ?= 2" support (Elvis assignment): should be expanded to "a = a == null ? 2 : a"

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Major
    • Resolution: Fixed
    • None
    • 3.0.0-alpha-1, 2.6.0-alpha-1
    • syntax
    • None

    Description

      I've suggested last week the creation of the "?:=" constructor in Groovy:

      https://jira.codehaus.org/browse/GROOVY-5291

      It was rejected and a new JIRA was requested to be created with a new operator.

      Then, I've talked to the Grails users in their mailing list to get some feedback, which can be read here:

      http://grails.1312388.n4.nabble.com/Help-improving-Groovy-syntax-tt4384137.html

      Then, Phil DeJarnett has suggested using "?=" instead of "?:=". Not only I preferred this suggestion, but I was changed my mind about its meaning too.

      It would be used as a caching/memoization operator mostly. It would be similar to Ruby's "||=", except for this specific situation:

      Ruby:

      a = nil
      a ||= false # a will be false
      a ||= true # a will be true
      

      That is why "a ||= value" is expanded to "a = a || value"

      But for caching/memoization, I'd prefer "a ?= value" to be expanded to "a = a == null ? value : a". This way we would have:

      Proposed Groovy syntax:

      def a = null
      a ?= false; assert a == false
      a ?= true; assert a == true
      
      a = null; a ?= new Object(); assert a instanceof Object
      

      I'll actually fill a new ticket on Ruby Redmine too for proposing the same syntax and semanthics

      Attachments

        Issue Links

          Activity

            People

              daniel_sun Daniel Sun
              rosenfeld Rodrigo Rosenfeld Rosas
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: