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

Prototype based OO with Groovy

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Minor
    • Resolution: Fixed
    • 1.0-JSR-6
    • 1.6.5, 1.7-beta-2
    • None
    • None
    • Windows 2000 (actually the RFE is generic).

    Description

      Part of the attraction of languages such as Groovy, JRuby is flexible method dispatching (which is part of metaprogramming). How about Self or JavaScript style prototype based OOP with Groovy? With the addition of a class like ProtoObject class (attached ProtoObject.java), it is possible to do prototype based OOP with Groovy.

      With ProtoObject, it is possible to write Groovy scripts like the one below:

      // create a prototype object
      def p = new ProtoObject();
      // add "method" to it.
      p.func =

      { self -> println("hello from " + self) }

      // create another object
      def d = new ProtoObject();
      d.greet =

      { println "hello world" }

      // set prototype to be "p"
      d._proto_ = p

      // prints "hello world"
      d.greet();
      // calls p.func (because of _proto_)
      d.func()

      The ProtoObject class is similar to Groovy's Expando. But, Expando sets current ("this") object as delegate to the Closure – and therefore will not work property with multithreading. In the ProtoObject class, I'm passing "this" as first argument to Closure. Besides, while a closure's delegate is used for method search within closure code, property access is not direct (user has to write delegate.property anyway) - so having explicit "self" as first argument is probably okay.

      Attachments

        1. ProtoObject.java
          3 kB
          Sundararajan

        Activity

          People

            blackdrag Jochen Theodorou
            sundararajan Sundararajan
            Votes:
            2 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: