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

Add "a ?:= 2" support: should be expanded to "a = a ?: 2"

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Major
    • Resolution: Duplicate
    • None
    • None
    • syntax
    • None

    Description

      This would allow the very common useful idiom found in Ruby:

      variable ||= value
      

      Currently we have to write code like this in Groovy:

      def myMap = [:]
      
      if (condition) (myMap[someLongNameObject.getKeyId()] = myMap[someLongNameObject.getKeyId()] ?: []) << someNewValue
      

      Also, if getKeyId() is costly or shouldn't get called more than once for some reason, we would have to write it like:

      def myMap = [:]
      if (condition) {
        def key = someLongNameObject.getKeyId()
        (myMap[key] = myMap[key] ?: []) << someNewValue
      }
      

      When it could be simplified as this:

      if (condition) (myMap[someLongNameObject.getKeyId()] ?:= []) << someNewValue
      

      Attachments

        Issue Links

          Activity

            People

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

              Dates

                Created:
                Updated:
                Resolved: