1

What is the purpose of runtime mixins in groovy?

Mixins overall one of the ways to add functionallity to class without multiple inheritance issues. But what is its purpose in Groovy? Traits can do the same.

Annotation @Mixin is considered deprecated at all. Will runtime mixins have the same fate one day?

lapots
  • 12,553
  • 32
  • 121
  • 242

2 Answers2

0

Runtime mixins give us the ability to add methods to existed classes at runtime. The important part of the answer is "existed" and "runtime".

So, you can easily add new methods to any 3rd party library at runtime.

SerCe
  • 5,826
  • 2
  • 32
  • 53
  • I can do that with categories blocks and metaclasses. – lapots Mar 25 '16 at 14:06
  • @user1432980, Metaclasses are a really "unsafe" way to perform this functionality. Categories work only for blocks of code, so they solve other problems. – SerCe Mar 25 '16 at 14:13
0

Actually, recently I found a case where using mixins helped me a lot.

String.metaClass {
    invokeMethod {
        String name, args ->
            System.out.println "[$name] invokation with $args"
    }
}

class GroovyInterceptableWrapper 
    implements GroovyInterceptable {
}


String.mixin(GroovyInterceptableWrapper)

Though again if I used there trait instead of class and then invoked withTraits I would have achieved the same result.

lapots
  • 12,553
  • 32
  • 121
  • 242