• +91 9723535972
  • info@interviewmaterial.com

Kotlin Interview Questions and Answers

Question - How does the reified keyword in Kotlin work?

Answer -

In an ordinary generic function like myGenericFun, you can't access the type T because it is, like in Java, erased at runtime and thus only available at compile time. Therefore, if you want to use the generic type as a normal Class in the function body you need to explicitly pass the class as a parameter like the parameter c in the example.

fun myGenericFun(c: Class)
By marking a type as reified, we’ll have the ability to use that type within the function.

As for a real example, in Java, when we call startActivity, we need to specify the destination class as a parameter. The Kotlin way is:

inline fun Activity.startActivity() {
    startActivity(Intent(this, T::class.java))
}
You can only use reified in combination with an inline function. Such a function makes the compiler copy the function's bytecode to every place where the function is being used (the function is being "inlined"). When you call an inline function with reified type, the compiler knows the actual type used as a type argument and modifies the generated bytecode to use the corresponding class directly. Therefore calls like myVar is T become myVar is String (if the type argument were String) in the bytecode and at runtime.

Comment(S)

Show all Coment

Leave a Comment




NCERT Solutions

 

Share your email for latest updates

Name:
Email:

Our partners