2

The official Kotlin docs and this answer do a great job of explaining how Kotlin reified allows us to change something like:

myJsonString.toData(MyDataClass::class)

To:

myJsonString.toData<MyDataClass>()

But I don't think either do a good job of explaining the motivation. Is the reified function only preferable because it saves a few characters? Or are there other benefits to not having to pass the class in as a parameter?

aaronstacy
  • 6,189
  • 13
  • 59
  • 72

3 Answers3

5

One more advantage of reified type parameters is that they provide full type information, including type arguments, when the type is known at compile time.

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>>>()
java.lang.Integer
java.util.List<? extends java.lang.String>

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

hotkey
  • 140,743
  • 39
  • 371
  • 326
4

The other benefit is that the type parameter can be inferred. For example:

fun foo(myData: MyDataClass) { ... }

foo(myJsonString.toData()) // no need to specify MyDataClass at all
yole
  • 92,896
  • 20
  • 260
  • 197
1

The motivation is type erasure in the end. Generics on the JVM are cool but only help at compile time. With reified, you can make generic types available at runtime. This results in cleaner APIs as demonstrated in this post and yole's answer, cleaner DSLs (they utilize reified a lot), and certainly also easier implementations that rely on type information which would be erased normally as shown by hotkey.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • For me, "knowing the type at compile time within the method" isn't a motivation by itself. Things like typing less, better runtime performance, fewer classes in the class loader, these seem like motivations on their own. I probably just don't have enough experience for that to be intrinsically valuable, but AFAICT fewer type annotations (@yole's point) and understanding a type's hierarchy of generic params (@hotkey's point) both still fall under the "typing less" motivation. And once again, that's fine and valuable, I'm just wondering if there's anything else. – aaronstacy Mar 04 '19 at 14:41