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?
"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.
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(
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With