2

Say I have a function

def method1(MyClass2 mc2) {...}

and I call it with an object of type MyClass1. Is there a way that I can specify how to implicitly convert from MyClass1 to MyClass2, so that the method call will work without having to explicitly say method1(mc1 as MyClass2)?

Kyle
  • 21,377
  • 37
  • 113
  • 200

1 Answers1

4

If MyClass1 doesn't implement/extend MyClass2, there isn't anything that I'm aware of that'll do the "as MyClass2" conversion without the old standby Java method overloading. Explicitly overloading the method with the signature including MyClass1:

def method1(MyClass1 mc1) { 
    method1(mc1 as MyClass2)
}

The other, more groovy, alternative is to not explicitly type method1 so that it doesn't demand that you have an instance of MyClass2:

def method1(mc) {
    // do stuff and let mc walk/talk/quack like MyClass2
    // or even do the "as MyClass2" in this method if you need it for something further down.
}
Ted Naleid
  • 26,511
  • 10
  • 70
  • 81
  • 3
    you could override the `Object asType( Class clazz )` method, to write a custom converter to handle `myObj1 as MyClass2` http://mrhaki.blogspot.com/2009/11/groovy-goodness-define-your-own-type.html – tim_yates Jan 17 '11 at 11:05