How does the reified k...
How does the reified k...
The reified
keyword in Kotlin is used in conjunction with inline functions to preserve type information at runtime. It allows you to access the actual type arguments passed to a generic function or type.
Here's how reified
works:
reified
can only be used with inline functions. Inline functions are expanded by the compiler at the call site, so the type information is available.
When you mark a type parameter as reified
, you can use it inside the function body to perform type checks and casts.
A common use case is to implement generic functions that behave differently based on the actual type argument passed to the function.
Example:
inline fun <reified T> isInstance(value: Any) = value is T
In this example, the isInstance
function checks if the given value
is an instance of the type T
. The reified
keyword allows us to use T
inside the function body to perform the is
check.
println(isInstance<String>("hello")) // true
println(isInstance<Int>(42)) // false
Another example is using reified
with the when
expression:
inline fun <reified T> getClassName() = when (T...
expert
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào