Reputation: 30578
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?
Upvotes: 29
Views: 6733
Reputation: 48439
The inline
functions declared without reified
type parameters can be called from Java as regular Java functions. But the ones declared with the reified
type parameters are not callable from Java.
Even if you call it using the reflection like following:
Method method = MyClass.class.getDeclaredMethod("foo", Object.class);
method.invoke(new MyClass(), Object.class);
You get the UnsupportedOperationException: This function has a reified type parameter and thus can only be inlined at compilation time, not called directly.
If you have access to the code of the function, removing the reified
modifier in some cases works. In other cases, you need to make adjustment to the code to overcome the type erasure.
Upvotes: 3
Reputation: 148189
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.
Upvotes: 39