Search code examples
statickotlincompanion-objectkotlin-companion

how to access outer class' javaClass.simpleName from companion object in kotlin?


I would like to be able to access the simpleName of my class from it's companion object.

I would like this:

val o1 = Outer("foo")
val o2 = Outer("bar")

to print the following output:

Outer: hello
Outer: foo
Outer: bar

The actual use case would be this in java:

class Outer {
    static final String TAG = Outer.class.simpleName();
    // and now I'm able to use Outer.TAG or just TAG in both static and non-static methods
}

I tried 2 things:

  1. assign Outer's simpleName to the companion object's COMPANION_TAG and then use COMPANION_TAG from companion's init and all over Outer's functions. I can access COMPANION_TAG from everywhere I need, but unfortunately I can only get "Companion" and not "Outer" this way.

  2. access Outer.OUTER_TAG from the companion object's init. Here the problem is that I can't find the way to access it.

Here's the code:

class Outer(str: String) {
    private val OUTER_TAG = javaClass.simpleName
    companion object {
        @JvmStatic val COMPANION_TAG = PullDownAnimationLayout.javaClass.simpleName // gives "Companion" :(
        init {
            // how can I access OUTER_TAG?
            Log.d(OUTER_TAG, "hello") // this gives an error
        }
    }
    init {
        Log.d(OUTER_TAG, str) // Outer: ... :)
        Log.d(INNER_TAG, str) // Companion: ... :(
    }
}

val o1 = Outer()
val o2 = Outer()

Solution

  • In order to achieve this in Kotlin,

    class Outer {
        static final String TAG = Outer.class.simpleName();
        // and now I'm able to use Outer.TAG or just TAG in both static and non-static methods
    }
    

    It should be

    class Outer {
        companion object {
            val Tag = Outer::class.java.simpleName
            val Tag2 = Outer.javaClass.simpleName // This will not work
        }
    }
    
    println(Outer.Tag)  // print Outer
    println(Outer.Tag2) // print Companion
    

    I think you misunderstand what companion is. companion is similar to Java static. See this discussion.