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

Null-safe dereference operator not available for subscript operator access to properties or array/list elements

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 1.6, 1.6.1, 1.6.2, 1.6.3, 2.4.0-beta-4
    • 3.0.0-alpha-1
    • groovy-runtime
    • None

    Description

      The null-safe deref operator causes compiler errors if it is used with the subscript operator.

      Take the following example:

      def obj = [name:'Marc Palmer', occupation:'Whining user', ]
      
      println obj?.name
      

      This is fine. However if you want to use the subscript operator for property access:

      def obj = [name:'Marc Palmer', occupation:'Whining user', ]
      def propName = 'name'
      println obj?[propName]
      

      You get errors. Of course you can workaround this with:

      def obj = [name:'Marc Palmer', occupation:'Whining user', ]
      def propName = 'name'
      println obj?.getAt[propName]
      println obj?."$propName"
      

      But this is quite ugly if you are in a situation where you need/want to use subscript, and also if this is done properly then we also get nullsafe deref of arrays, lists and sets, especially if they are nested:

      def myList = null
      println myList?[0]?['name']
      

      Without this you have to write the equivalent of:

      def myList = null
      println myList?.getAt(0)?.getAt('name')
      

      Can't Groovy do this for us?

      Attachments

        Activity

          People

            daniel_sun Daniel Sun
            marc@anyware.co.uk Marc Palmer
            Votes:
            2 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: