In Kotlin, the ‘reified‘ keyword is used to make a type parameter of a generic function available as a real type inside the function body at runtime. It is used in conjunction with ‘inline‘ functions.
When you declare a generic function in Kotlin, the type parameter is not actually available as a real type at runtime. Instead, it is erased by the compiler, which means that you cannot perform any runtime checks or operations based on that type.
The ‘reified‘ keyword allows you to work around this limitation by making the type parameter available as a real type inside the function body. This enables you to perform operations at runtime that would normally be impossible with a generic type parameter.
Here is an example of a generic function that filters a list based on a given predicate:
fun <T> filterList(list: List<T>, predicate: (T) -> Boolean): List<T> {
return list.filter { element -> predicate(element) }
}
If you wanted to call this function with a lambda that checks for the presence of a certain string in a list of strings, you would have to specify the type parameter like this:
val stringList = listOf("cat", "dog", "fish")
val filteredList = filterList<String>(stringList) { element -> element.contains("c") }
With ‘reified‘, you can avoid specifying the type parameter and use it as an actual type inside the function:
inline fun <reified T> filterList(list: List<T>, predicate: (T) -> Boolean): List<T> {
return list.filter { element -> predicate(element) }
}
val stringList = listOf("cat", "dog", "fish")
val filteredList = filterList(stringList) { element -> element.contains("c") }
This allows you to write more concise code and makes it easier to perform runtime checks based on the type parameter. For example, you can check if a given object is of the same type as the elements in a list:
inline fun <reified T> containsType(list: List<Any>): Boolean {
return list.any { it is T }
}
val stringList = listOf("cat", "dog", "fish")
val containsString = containsType<String>(stringList) // true
val containsInt = containsType<Int>(stringList) // false
Note that ‘reified‘ can only be used with ‘inline‘ functions, because the actual type of the type parameter needs to be available at compile time.