How can I call Kotlin methods with reified generic

2019-02-11 22:47发布

问题:

I have the following method in Kotlin:

inline fun <reified T> foo() {

}

If I try to call this from Java like this:

myObject.foo();

OR like this:

myObject.<SomeClass>foo();

I get the following error:

java: foo() has private access in MyClass

How can I call the foo method from Java?

回答1:

There's no way to call Kotlin inline functions with reified type parameters from Java because they must be transformed and inlined at the call sites (in your case, T should be substituted with the actual type at each call site, but there's much more compiler logic for inline functions than just this), and the Java compiler is, expectedly, completely unaware of that.