Groovy - @Delegate

Groovy supports the @Delegate annotation.

With this annotation we can import all the methods of the class the annotation is used for.

class Phone {
    def dial(String number) { "dialing $number" }
}

class Camera {
    def takePicture() { "taking picture" }
}

class SmartPhone {
    @Delegate Phone phone = new Phone()
    @Delegate Camera camera = new Camera()
}

SmartPhone sp = new SmartPhone()

println sp.dial('555-1234')
println sp.takePicture()

assert sp.dial('555-1234') == 'dialing 555-1234'
assert sp.takePicture() == 'taking picture'
​

Output of Script

 315 ms
dialing 555-1234
taking picture



Comments

Popular posts from this blog

Array and Object Creation - JavaScript

Groovy Tuples

அவன் ஏன் கூலியானான்?