Can I override the cast operator in Groovy?

I need something similar to this:

interface Bar { 
    def doSomething()
}

class Foo { // does not implement Bar.

    def doSomethingElse() {
    }

    Bar asBar() { // cast overload
        return new Bar() {
            def doSomething() {
                doSomethingElse()
            }
        }
    }

}

Foo foo = new Foo()
Bar bar = foo as Bar
bar.doSomething()

Is there something similar in Groovy?

+3
source share
2 answers

Have you tried to override the method Object#asType(Class)?

+4
source

Use the coercion operator (as)

class Identifiable {
    String name
}
class User {
    Long id
    String name
    def asType(Class target) {                                              
        if (target==Identifiable) {
            return new Identifiable(name: name)
        }
        throw new ClassCastException("User cannot be coerced into $target")
    }
}
def u = new User(name: 'Xavier')                                            
def p = u as Identifiable                                                   
assert p instanceof Identifiable                                            
assert !(p instanceof User) 

More on how this works here: -

http://groovy-lang.org/operators.html#_coercion_operator

0
source

All Articles