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

Documentation incorrect for Object#with

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Minor
    • Resolution: Fixed
    • 1.7.10
    • 1.8.1, 1.9-beta-1, 1.7.11
    • None
    • None

    Description

      The documentation for Object#with suggests using it to initialize objects, but the examples it provides are not correct. They assume that #with returns the object, when it actually returns the result of the closure.

      The first example works because StringBuilder#append serendipitously returns the object, and the closure returns the result of the last #append.

      def b = new StringBuilder().with {
        append('foo')
        append('bar')
      }
      
      assert b instanceof StringBuilder
      

      The second example does not work correctly, since the closure returns the result of the assignment to the lastName property.

      class Person { def firstName, lastName }
      
      def p = new Person().with {
         firstName = 'John'
         lastName = 'Doe'
      }
      
      assert p instanceof Person
      

      Modifying the examples so that the closures explicitly return the object would make the documentation correct.

      def b = new StringBuilder().with {
      
        append('foo')
        append('bar')
        
        return it
      }
      
      assert b instanceof StringBuilder
      
      class Person { def firstName, lastName }
      
      def p = new Person().with {
      
        firstName = 'John'
        lastName = 'Doe'
        
        return it
      }
      
      assert p instanceof Person
      

      Attachments

        Activity

          People

            guillaume Guillaume Sauthier
            justin.piper@gmail.com Justin Piper
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: