Câu hỏi phỏng vấn Kotlin
Câu hỏi

How does the reified k...

Câu trả lời

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:

kotlin Copy
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.

kotlin Copy
println(isInstance<String>("hello")) // true
println(isInstance<Int>(42)) // false

Another example is using reified with the when expression:

kotlin Copy
inline fun <reified T> getClassName() = when (T...
expert

expert

Gợi ý câu hỏi phỏng vấn

middle

What is the difference between suspending vs. blocking?

middle

What is the idiomatic way to deal with null able values, referencing or converting them?

middle

How would you create a singleton with parameter in Kotlin?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào