Jooo21
Jooo21

Reputation: 167

Generic vs Any function in Kotlin

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?

Upvotes: 4

Views: 505

Answers (1)

Sweeper
Sweeper

Reputation: 270840

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.

Upvotes: 8

Related Questions