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

Traits cannot modify their internal variables

    XMLWordPrintableJSON

    Details

    • Type: Bug
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: 2.3.0-beta-1
    • Fix Version/s: 2.3.0-beta-2
    • Component/s: Compiler
    • Labels:
      None

      Description

      trait Level {
          int maxLevel
          int currentLevel = 0
          
          void foo() {
              if( currentLevel < maxLevel ) {
                  currentLevel += 1
              }
          }
      }
      
      class Leveller implements Level {
          Leveller() {
              maxLevel = 3
          }
      }
      
      def v = new Leveller()
      v.foo()
      v.foo()
      v.foo()
      v.foo()
      assert v.currentLevel == 3
      

      fails with

      Assertion failed: 
      
      assert v.currentLevel == 3
             | |            |
             | 0            false
             Leveller@1f757867
      

      But if you change the trait to:

      trait Level {
          int maxLevel
          int currentLevel = 0
          
          void foo() {
              if( Level__currentLevel < maxLevel ) {
                  Level__currentLevel += 1
              }
          }
      }
      

      It works...

      I'm guessing this is a bug, as the given example (http://beta.groovy-lang.org/docs/groovy-2.3.0-beta-1/html/documentation/core-traits.html#_private_fields) of:

      trait Counter {
          private int count = 0                   
          int count() { ++count }                 
      }
      class Foo implements Counter {}             
      def f = new Foo()
      assert f.count() == 1  
      

      doesn't work if you add:

      assert f.count() == 2
      

      to the bottom

        Attachments

          Activity

            People

            • Assignee:
              blackdrag Jochen Theodorou
              Reporter:
              tim_yates Tim Yates
            • Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: