• Android Video Tutorials

How does the reified keyword work in Kotlin?

"reified" is a special type of keyword that helps Kotlin developers to access the information related to a class at runtime. "reified" can only be used with inline functions. When "reified" keyword is used, the compiler copies the function’s bytecode to every section of the code where the function has been called. In this way, the generic type T will be assigned to the type of the value it gets as an argument.


In this example, we will see how "reified" is helpful to re-use our code and use the same function to perform similar kind of operation regardless of its passing argument.

For this example, we have created an Inline function and we are passing a generic "reified" argument T and from the main() of Kotlin, we are calling myExample() multiple times with different arguments.

// Declaring Inline function
inline fun <reified T> myExample(name: T) {
Name of your website -> "+name)    println("
Type of myClass: ${T::class.java}") } fun main() {    // calling func() with String    myExample<String>("www.tutorialspoint.com")    // calling func() with Int value    myExample<Int>(100)    // calling func() with Long value    myExample<Long>(1L) }


It will generate the following output −

Name of your website -> www.tutorialspoint.com

Type of myClass: class java.lang.String

Name of your website -> 100

Type of myClass: class java.lang.Integer

Name of your website -> 1

Type of myClass: class java.lang.Long