Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 312
Jooo21 Avatar asked Sep 20 '25 23:09

Jooo21


1 Answers

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.

like image 128
Sweeper Avatar answered Sep 22 '25 18:09

Sweeper