2

Say I have a class like this:

class Foo {
  def doFoo() {
    println "foo"
  }
}

And another like this:

class Bar {
  def doBar() {
    println "bar"
  }
}

And one more that looks like this:

class Baz {
  Foo foo = new Foo()
  Bar bar = new Bar()
}

With that example, what would it take to be able to use it like this:

Baz baz = new Baz()
baz.doFoo()
baz.doBar()

where the doFoo and doBar method calls simply delegate to the defined versions in their respective objects? Is there a way to do this with some kind of metaprogramming, or am I stuck defining each method individually as a wrapper?

Opal
  • 81,889
  • 28
  • 189
  • 210
Andy
  • 8,749
  • 5
  • 34
  • 59
  • Found another post that goes into more detail about AST transformations and traits: http://stackoverflow.com/a/23124968/493807 – Andy Dec 01 '16 at 14:13

1 Answers1

3

@Delegate is what you need:

class Foo {
  def doFoo() {
    println "foo"
  }
}

class Bar {
  def doBar() {
    println "bar"
  }
}

class Baz {
  @Delegate
  Foo foo = new Foo()
  @Delegate
  Bar bar = new Bar()
}

Baz baz = new Baz()
baz.doFoo()
baz.doBar()
Opal
  • 81,889
  • 28
  • 189
  • 210