Giới thiệu
reified là từ khóa đặc biệt cho phép truy xuất thông tin kiểu generic tại runtime. Chỉ dùng với inline function. Compiler copy bytecode hàm đến mọi chỗ gọi, thay thế type parameter T bằng kiểu thực tế của đối số.
Ví dụ
// Inline function với reified type parameter
inline fun <reified T> myExample(name: T) {
println("\nName of your website -> $name")
println("\nType of myClass: ${T::class.java}")
}
fun main() {
myExample<String>("www.tutorialspoint.com")
myExample<Int>(100)
myExample<Long>(1L)
}
Kết quả
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
Nhờ reified, bên trong hàm có thể dùng T::class.java để lấy Class object – điều không thể với generic thông thường do type erasure.