Why are Kotlin reified functions better?

kotlin generics
kotlin inline function
crossinline kotlin
kotlin reified constructor
cannot use 't' as reified type parameter. use a class instead.
kotlin-reified interface
kotlin generic extension function
in kotlin

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?

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?

How Reified Type makes Kotlin so much better, With reified , this could be simplified to just the generic type. // Function inline fun <reified T : Activity> Activity.startActivity( context: Context) { Reification is a workaround for type erasure: when the compiler inlines a function, it has access to the type information at the call site, and can substitute it there and then.   That's why you can use the type parameter to cast, access its Classobject, and other things that simply aren't possible if the function is called in the usual way.

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

Why are Kotlin reified functions better?, One more advantage of reified type parameters is that they provide full type information, including type arguments, when the type is known at� (1) Make the function inline and use the reified keyword before the type parameter. After doing this, the function can retain type information at runtime. You can only reify inline functions. When you inline a function, the compiler will replace every call to that function with the actual its actual bytecode (not just the address of the function).

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.

Introduction to Kotlin Generics: Reified Generic Parameters, Reified Generics in Kotlin The effect is that you can pass functions through parameters in a Duration: 5:48 Posted: Apr 18, 2019 Kotlin also doesn't support the static modifier, but it isn't needed in this case because main is a top-level function. Since Kotlin 1.3, the array-of-strings parameter for main is not required

Reified Types in Kotlin: how to use the type within a function (KAD 14), Normally this is solved by passing the class as a function parameter, making the code more Duration: 21:55 Posted: Mar 5, 2017 Better for what? Languages are a tool; you can have the world’s best screwdriver, but you’d still be screwed if you needed to hammer in a nail. Kotlin is a slightly higher level language than Java, allowing some more shorthand, compiling onto JVM

Kotlin Reified Types in Inline Functions, Simon Wirtz Blog - Kotlin Reified Types in Inline Functions - Read how Kotlin makes generic functions more readable by using reified generic types. Kotlin is inherently lightweight, clean and far less verbose, especially in terms of writing callbacks, data classes, and getters/setters. In other words, Kotlin is specifically designed to improve existing Java models by offering solutions to API design deficiencies. Kotlin addresses a number of Java’s weaknesses:

Kotlin Reified Generics: Explained - DEV, Kotlin's reified generics allow you to pretend that the generic is still there at make it seem like that: it just inlines the function call and replaces the generic parameter What's the best way to get something production-ready? The State of Kotlin. Why would I write a library in Kotlin? you might ask. If you have been using Kotlin for a while now you might think that you have everything within the Java ecosystem and it is not necessary to write anything new in Kotlin (apart from the application you are working on).

Comments
  • 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.