Osama Saqr’s Post

View profile for Osama Saqr, graphic

Senior Android Developer | FinTech | Pos developer | Emv payment@paysky

Kotlin Advanced KeyWords #2 Reified : The reified keyword in Kotlin is a powerful tool that allows you to access the type information of a generic parameter at runtime. Normally, generic type parameters in Kotlin are erased during compilation due to type erasure, meaning the type information is not available at runtime. However, by using the reified keyword in conjunction with an inline function, Kotlin allows you to preserve this type information. * When and Why Use reified You use reified when: You need to access or check the type of a generic parameter at runtime (e.g., for type checks or casting). You want to simplify type-specific operations, like creating instances of a type or filtering collections by type. reified works only within inline functions because the function body is substituted directly at *usecases 1-    Basic  usage : check type inline fun <reified T> isOfType(value: Any): Boolean {   return value is T } // Usage println(isOfType<String>("Hello")) // true println(isOfType<Int>("Hello"))   // false 2-    Instance Creation You can use reified to create new instances of the generic type: inline fun <reified T> createInstance(): T  { return T::class.java.getDeclaredConstructor().newInstance() }  // Usage  data class Example(val name: String = "Default") val instance = createInstance<Example>() println(instance) #kotlin_advanced_keywords

Mahmoud A. Attia

Senior Full Satck (.Net | Angular)

1mo

Useful tips

To view or add a comment, sign in

Explore topics