groovy (moved to ASF)
  1. groovy (moved to ASF)
  2. GROOVY-3525

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


    • 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, 2.4.0-beta-4
    • Fix Version/s: None
    • Component/s: groovy-runtime
    • Labels:
    • Number of attachments :


      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?


        No work has yet been logged on this issue.


          • Assignee:
            Marc Palmer


            • Created: