28

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?

Adam Arold
  • 29,285
  • 22
  • 112
  • 207

2 Answers2

36

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.

Ilya
  • 21,871
  • 8
  • 73
  • 92
hotkey
  • 140,743
  • 39
  • 371
  • 326
  • 2
    thanks a lot~ brb refactor java code bit by bit, to kotlin – mochadwi Feb 25 '19 at 18:13
  • To make the conversion easier you can define an overload which consumes a Class instead of the reified type in the implementation as an overload. ```kotlin inline fun help() = help(T::class.java); fun help(cls: Class) { ... } ``` This way you may call it via a reified generic in Kotlin and using class object in Java` – Mats Jun Mar 25 '21 at 18:11
1

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.

Yogesh Umesh Vaity
  • 41,009
  • 21
  • 145
  • 105