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

Traits should be able to hold constants

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Open
    • Major
    • Resolution: Unresolved
    • None
    • None
    • Compiler

    Description

      I can define constants on plain old interfaces; since they're implicitly public static final, just String PREFIX = 'asdf_' will get the job done.

      However, in a trait, while I can declare a constant and use it within the trait, I can't access that constant from outside the trait. Instead, I get this error (in static mode for better message; dynamic mode generates bytecode demonstrating the same semantic error):

      trait MyTrait {
        public static final String PREFIX = 'foo'
      }
      
      // in another class
      doStuff(MyTrait.PREFIX, data)
      
      [Static type checking] - No such property: PREFIX for class: java.lang.Class <com.example.MyTrait>
      

      The compiler seems to be treating what should be a distinct symbol MyTrait.PREFIX as a property access on the class MyTrait. I expected the PREFIX constant to be copied to the generated interface .class file and available as it would be on an interface. Instead, it appears that it's being put into the $Trait$Helper.class file. Perhaps the trait AST needs a special rule to recognize constants and route them suitably?

      Attachments

        Issue Links

          Activity

            People

              Unassigned Unassigned
              chrylis Christopher Smith
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

                Created:
                Updated: