0

I'm trying to reach a constant String value of the Class name. But I really don't understand why I get a modified String value. Here is the code that I'm working on:

class TestClass {
    companion object {
            @JvmField
            val TAG1: String = this::class.java.name as String
            val TAG2: String = this::javaClass.name 
    } 
}

In another class trying to reach the value like this:

class ComboClass {
    override fun onStart() {
       val tag1 = TestClass.TAG1
       val tag2 = TestClass.TAG2

       // tag1 "packagePath.TestClass$Companion"
       // tag2 "packagePath.TestClass$Companion"
    }
}

Why Am I getting packagePath.TestClass$Companion at the end of the String value? I'm expecting to get packagePath.TestClass

Thanks

Orcun Sevsay
  • 1,310
  • 1
  • 14
  • 44
  • 1
    Because `this` is the companion object of the class TestClass. It's not an instance of TestClass. https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects – JB Nizet Jan 27 '18 at 15:30

1 Answers1

2

Why Am I getting packagePath.TestClass$Companion at the end of the String value?

Companion objects have classes of their own, in this case the object is of type TestClass$Companion, so this::class.java.name as String and this::javaClass.name both give you the name of the companion object's class.

How to get TestClass

You will want to use TestClass::class.java.name and TestClass::javaClass.name instead to get TestClass

jrtapsell
  • 6,719
  • 1
  • 26
  • 49