Kotlin's reified function cannot be called from java.

Reified type parameters kotlin has the modifier reified. The official page is here

Reified can be given to genericsT and can be handled as an actual type class, so you can cast with T, check the instance of T with an if statement, etc. I will.

For example, it can be defined as follows.

// ListExt.kt

inline fun <reified T> List<T>.filterInstance(): List<T> {
    val destination = mutableListOf<T>()
    this.forEach {
        if (it is T) destination.add(it)
    }
    return destination
}

If you call this from kotlin


val nums = listOf(1, 2f, 3, 4f)
val ints = nums.filterIsInstance<Int>() // [1, 3]

But when I try to call this from java


List nums = Arrays.asList(1, 2f, 3, 4f);
List ints = ListExtKt.filterIsInstance(nums); // error: filterIsInstance has private access in ListExtKt

Reified in kotlin can only be given to inline functions, and inline expansion makes it possible to access the actual typeclass. When you call the kotlin inline function from java, the inline function is called directly, so it will not be expanded inline. Therefore, it seems that an error occurs when trying to call a function with reified from java.

Recommended Posts

Kotlin's reified function cannot be called from java.
[Java] Protected methods cannot always be called from within a subclass
Java Stream cannot be reused.
Call Kotlin's sealed class from Java
Java to be involved from today
Java cannot be installed on Ubuntu 13.04
[Rails] Rails new cannot be done from Docker
Java code that cannot be used from Kotlin (for in-house study sessions)
[Android] Call Kotlin's default argument method from Java
[Java] Scenes that cannot be reassigned (substantially final)
Minecraft BE server development from PHP to Java
Why Java String typeclass comparison (==) cannot be used