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

property read accessor defined via metaClass does not work without parameter list terminator in closure

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Minor
    • Resolution: Fixed
    • 1.5.4
    • 1.7.9
    • None
    • None
    • Mac OSX 10.4 Darwin 8.11.1, Groovy 1.5.4, Java 1.5.0_07

    Description

      The following is listed in the usage guide as an example of adding a property to an existing class:

      class Book {
          String title
      }
      
      def properties = Collections.synchronizedMap([:])
      
      Book.metaClass.setAuthor = { String value ->
         properties[System.identityHashCode(delegate) + "author"] = value
      }
      Book.metaClass.getAuthor = {->
         properties[System.identityHashCode(delegate) + "author"]
      }
      

      In other contexts, the -> is generally considered optional. However, if you do not use the -> list terminator in the get method closure, the read accessor does not work. For example, if you instead define getAuthor like:

      Book.metaClass.getAuthor = {
         properties[System.identityHashCode(delegate) + "author"]
      }
      

      the following occurs when you call the property accessor:

      book = new Book()
      book.author = "foo" // works
      println book.author // does not work
      
      Caught: groovy.lang.MissingPropertyException: No such property: author for class: Book
              at Book.getProperty(propertyTest.groovy)
              at foo.run(propertyTest.groovy:15)
              at foo.main(propertyTest.groovy)
      

      I'm new to Groovy and may very well be missing something, but this does not seem like expected behavior.

      Attachments

        Activity

          People

            guillaume Guillaume Sauthier
            ssayles Scott Sayles
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: