Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 616
Adam Arold Avatar asked Mar 11 '17 23:03

Adam Arold


People also ask

How do you use reified on Kotlin?

"reified" is a special type of keyword that helps Kotlin developers to access the information related to a class at runtime. "reified" can only be used with inline functions. When "reified" keyword is used, the compiler copies the function's bytecode to every section of the code where the function has been called.

What does reified mean in Kotlin?

Reified Generics in Kotlin The effect is that you can pass functions through parameters in a way that the type arguments can't be erased, or reified. A reified generic type parameter ends up taking our Generic Class-as-a-Parameter Pattern signature from this: fun <T: Mammal> printAnimalResultFiltered(

What are reified generics?

Reified Generics is a generics system that makes generics type information available at runtime. C# is one language that supports Reified Generics natively, as opposed to Java's Type-Erased Generics.

What is inline fun in Kotlin?

An Inline function is a kind of function that is declared with the keyword "inline" just before the function declaration. Once a function is declared inline, the compiler does not allocate any memory for this function, instead the compiler copies the piece of code virtually at the calling place at runtime.


1 Answers

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.

like image 68
hotkey Avatar answered Oct 20 '22 12:10

hotkey