Kyle
Kyle

Reputation: 22035

Can I overload the implicit type conversions in Groovy?

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)?

Upvotes: 2

Views: 779

Answers (1)

Ted Naleid
Ted Naleid

Reputation: 26801

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.
}

Upvotes: 4

Related Questions