4

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?

Jooo21
  • 110
  • 6

1 Answers1

8

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • 2
    a few more examples: `listOf()` will give `List` and `EmptyList`. `listOf(1)` will give `List` and `SingletonList`. `listOf(1, 2)` will give `List` and `ArrayList`. – AlexT Dec 04 '21 at 11:13
  • does it mean using generic is always better than using Any? – Jooo21 Dec 04 '21 at 11:56
  • @Jooo21 Well, depends on what you want, really. If you want the compile time type, then sure, using generics will get you that. – Sweeper Dec 04 '21 at 12:02