carlspring
carlspring

Reputation: 32607

Groovy + Java interface inheritance issue

If B implements A (Java classes), and ABUtils has a method:

public A getBar(String s)
{
    return new B(s);
}

what's wrong with the following code:

import A
import B

def foo = ABUtils.getBar("blah");

Why would it produce:

org.codehaus.groovy.runtime.typehandling.GroovyCastException:
    Cannot cast object 'blah' with class 'B' to class 'A'

Upvotes: 0

Views: 424

Answers (1)

Will
Will

Reputation: 14529

No problem at all.

A.java:

public interface A {}

B.java:

public class B implements A {}

ABUtil.groovy:

class ABUtils {
  A getBar() { new B() }
}

new ABUtils().bar.with {
  assert it instanceof A
  assert it instanceof B
}

Compile and run:

$ javac *.java && groovy AB.groovy 
$ 

Upvotes: 1

Related Questions