0

I'd like to know if there is any way to add methods to library classes using Groovy traits.

From what I read here @Mixin is used for this, or you can use the runtime mixin approach with metaclass. Since @Mixin is now deprecated in favor of traits, any chance to achieve the same behavior by using traits or is runtime mixin the only option?

Thank you

Community
  • 1
  • 1
user4132657
  • 207
  • 1
  • 3
  • 10

1 Answers1

0

Groovy also supports implementing traits dynamically at runtime. It allows you to "decorate" an existing object using a trait.

You can decorate an object, however, I am afraid that it is not possible to decorate a class so that all its instances have the method available. See below a simple example that may help you or find more details here.

trait Extra {
    String extra() { "I'm an extra method" }            
}

class Something {                                       
    String doSomething() { 'Something' }                
}

def s = new Something() as Extra                        

assert s.extra() == "I'm an extra method"                                               
assert s.doSomething() == 'Something'
pgiecek
  • 7,970
  • 4
  • 39
  • 47