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

Issue a warning when accessing static fields that are "shadowed" by get() methods

Agile BoardAttach filesAttach ScreenshotVotersWatch issueWatchersCreate sub-taskLinkCloneUpdate Comment AuthorReplace String in CommentUpdate Comment VisibilityDelete Comments
    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Resolved
    • Minor
    • Resolution: Fixed
    • 4.0.21
    • 5.0.0-alpha-9, 4.0.22
    • Compiler
    • None

    Description

      Introduction

      When having a static field in a class that is retrieved by lambda, a get() method is invoked instead. See the example code below, where DataClass#get is called instead of returning the value of the STR field.

      class StaticPropertyIssueTest {
          static def STR = "test"
      
          static void main(String[] args) {
              def dataClass = new DataClass(value: "test")
      
              dataClass.with {
                  assert value == STR
              }
          }
      }
      
      class DataClass {
          String value
          String get(String str) { "Hello" }
      }  

      In the https://issues.apache.org/jira/browse/GROOVY-11144 discussion, I learned that this is an expected behaviour.

      The main reason why I find this behaviour counter-intuitive is, that if the DataClass comes from a library, I have no clue the DataClass#get method exists. This problem always happens with AVRO-generated classes in particular, where every class extending the

      org.apache.avro.specific.SpecificRecordBase

      implements a

      public Object get(String fieldName) { ... }

      method. 

      Actually, the get() method may even come from my own code, but I just don't realise it will be called because I simply only see the STR static field in my currently implemented class.

      Improvement proposal

      Since this is the intended way Groovy is supposed to work, it would be amazing if the compiler could issue a warning that the static field's retrieval is shadowed by a getter method that will be called rather than returning the static field's value.

      In my eyes, this is something one simply does not expect. A compiler warning together with advice, that we must qualify the field retrieval by this keyword or by a class name, would help to understand the root cause of a misbehaving code.

      Attachments

        Issue Links

        Activity

          This comment will be Viewable by All Users Viewable by All Users
          Cancel

          People

            emilles Eric Milles
            lobodpav Pavel Lobodinský
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved:

              Slack

                Issue deployment