How can I call Kotlin methods with reified generics from Java?
Asked Answered
S

2

29

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?

Scleroprotein answered 11/3, 2017 at 23:10 Comment(0)
D
38

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.

Dissolute answered 11/3, 2017 at 23:59 Comment(2)
thanks a lot~ brb refactor java code bit by bit, to kotlinProfessor
To make the conversion easier you can define an overload which consumes a Class<T> instead of the reified type in the implementation as an overload. kotlin inline fun <reified T> help() = help(T::class.java); fun <T> help(cls: Class<T>) { ... } This way you may call it via a reified generic in Kotlin and using class object in Java`Heflin
E
2

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.

Euphorbia answered 25/3, 2021 at 15:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.