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