3

I need something as similar as possible 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 like this in Groovy?

fernacolo
  • 7,012
  • 5
  • 40
  • 61

2 Answers2

5

Have you tried overriding Object#asType(Class) method ?

Riduidel
  • 22,052
  • 14
  • 85
  • 185
  • Thanks. That should be placed on http://groovy.codehaus.org/Operator+Overloading. It would prevent newbies like me from placing such questions. – fernacolo Mar 09 '11 at 15:11
  • 2
    @fernacolo it's a wiki, so you could do it :-) – tim_yates Mar 09 '11 at 17:00
  • It is briefly (very briefly) mentioned here http://groovy.codehaus.org/Operators#Operators-ObjectRelatedOperators So I guess that's where it could do with expanding... – tim_yates Mar 10 '11 at 15:19
0

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 details on how this works here:-

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

Dave00Galloway
  • 609
  • 1
  • 6
  • 20