Home > database >  Generic vs Any function in Kotlin
Generic vs Any function in Kotlin

Time:12-04

What is the difference between

inline fun <reified T> T.TAG(): String = T::class.java.simpleName

and

fun Any.TAG(): String = this::class.java.simpleName

is there any difference between using generic and Any as function parameter or as extended function class name?

CodePudding user response:

There is a difference.

inline fun <reified T> T.TAG1(): String = T::class.java.simpleName
fun Any.TAG2(): String = this::class.java.simpleName

TAG1 would get the compile-time type as the type of T is determined at compile time, and TAG2 would get the runtime type. this::class is similar to this.getClass() in Java.

For example:

val x: Any = "Foo"

x.TAG1() would give you Any::class.java.simpleName, and x.TAG2() would give you String::class.java.simpleName.

  • Related