« Return to Thread: mixins etc.

RE: mixins etc.

by Dierk König :: Rate this Message:

Reply to Author | View in Thread

RE: [groovy-dev] mixins etc.

cool ;-)

Thanks a lot for the implementation and the comprehensive
description!

| So what is mixin?
|
| Mixin is usual category-like class, which provides methods to
| extend some (or several) existing classes.
|
| class ArrayListExt {
|    static def newArrayListMethod (ArrayList self) {
|         "result of newArrayListMethod "
|    }
| }

... except that categories can be used to define
methods on a combination of classes that work together
to fulfill a common purpose. E.g.
defining something like

class IntCodec {
    static String encode (Integer self) { ... }
    static Integer decode (String self) { ... }
}

is not possible with mixins, since they only affect
one class at a time.

Right?

Also, categories have a scope of use. Mixins don't,
right?

Is there also any difference in the affected threads?
(I vaguely remember this has been discussed on the
list before... sorry)

| simple use of it
|
| ArrayList.mixin ArrayListExt

how about setting the scope like

ArrayList.mixin (ArrayListExt) {
    // new methods available here
}
// but not here anymore

?

| @Mixin(MyClassExt)
| class MyClass {
|      def result () {
|          longRunningJavaMethod ()
|      }
| }
|
| and write for example in Java
|
| public MyClassExt {
|          public static Set<Collection> longRunningJavaMethod (MyClass
| self) { /// }
| }

so cool and very powerful ;-)

reminds me on my old Ruby days...


| Another nice feature for groovy objects is ability to do per
| instance mixins

dito

| 1) Methods of the class and super classes (including all
| their modifications except categories)
| 2) DGM methods
| 3)
| 4) EMC methods
| 5) methods of categories in use

well explained!

Now how about this:

class A { def foo() {'A'} }
class B extends A { def foo() {'B'} }      // subclass overrides method

class M { static void foo(A self) {'M'} }  // mixin redefines method

A.mixin M

println( new B().foo() )

???? %-)

cheers
Dierk

 « Return to Thread: mixins etc.