6

I'm trying to achieve following:

class A {
  def foo() { "foo" }
}

class B {
  def bar() { "bar" }
}

A.mixin B
def a = new A()

a.foo() + a.bar()

with one significant difference - I would like to do the mixin on the instance:

a.mixin B

but this results in

groovy.lang.MissingMethodException: No signature of method: A.mixin() is applicable for argument types: (java.lang.Class) values: [class B]

Is there a way to get this working like proposed in the Groovy Mixins JSR?

tim_yates
  • 167,322
  • 27
  • 342
  • 338
david
  • 2,529
  • 1
  • 34
  • 50

1 Answers1

8

You can do this since Groovy 1.6

Call mixin on the instance metaClass like so:

class A {
  def foo() { "foo" }
}

class B {
  def bar() { "bar" }
}

def a = new A()
a.metaClass.mixin B

a.foo() + a.bar()
Dónal
  • 185,044
  • 174
  • 569
  • 824
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • Thanks a lot Tim! So I have to wait a bit till Groovy 1.7.1 is part of Grails (let's hope in 1.3)... – david Mar 21 '10 at 20:17
  • 1
    Just tried it out, and it works in 1.6.3 as well (which I believe is the version of groovy that grails 1.2 uses) :-) – tim_yates Mar 21 '10 at 22:17
  • 1
    Yes, this feature was added in Groovy 1.6 http://www.infoq.com/articles/groovy-1-6 – Dónal Mar 22 '10 at 14:36