The official Kotlin docsthis answer很好地解释了Kotlin reified如何允许我们更改以下内容:

myJsonString.toData(MyDataClass::class)

至:
myJsonString.toData<MyDataClass>()

但是我认为这两者都不能很好地解释动机。是否只使用reified函数,因为它节省了几个字符?还是不必将类作为参数传递还有其他好处吗?

最佳答案

标准化类型参数的另一个优点是,当在编译时知道类型时,它们可以提供完整的类型信息,包括类型参数。

abstract class TypeReference<T> : Comparable<TypeReference<T>> {
    val type: Type =
        (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]

    override fun compareTo(other: TypeReference<T>) = 0
}

inline fun <reified T: Any> printGenerics() {
    val type = object : TypeReference<T>() {}.type
    if (type is ParameterizedType)
        type.actualTypeArguments.forEach { println(it.typeName) }
}
printGenerics<HashMap<Int, List<String>>>()



另请:How to get actual type arguments of a reified generic parameter in Kotlin?

08-05 19:29
查看更多