groovy
  1. groovy
  2. GROOVY-3525

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

    Details

    • Type: Bug Bug
    • Status: Open Open
    • Priority: Major Major
    • Resolution: Unresolved
    • Affects Version/s: 1.6, 1.6.1, 1.6.2, 1.6.3
    • Fix Version/s: None
    • Component/s: groovy-runtime
    • Labels:
      None
    • Number of attachments :
      0

      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?

        Activity

        There are no comments yet on this issue.

          People

          • Assignee:
            Unassigned
            Reporter:
            Marc Palmer
          • Votes:
            4 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

            • Created:
              Updated: