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

1

5

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()
Upheaval answered 31/1, 2018 at 2:15 Comment(1)
Accessing OUTER_TAG in companion gives error because it is a class variable. You cannot access it without an instance.Anarchist
A
6

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.

Anarchist answered 31/1, 2018 at 3:27 Comment(4)
I understand that. That's the exact reason I'm trying to use it. I want to print the version of the lib only once, not every time an Outer object is created, that's the reason I use the init {} of the companion, instead of a static {} code block of javaUpheaval
@Upheaval Does Outer::class.java.simpleName work for you though?Anarchist
yes it works. I'm not sure however if I need the @JvmStatic before it or not.Upheaval
@Upheaval You don't need JvmStatic unless there is a specific need from Java side. It is need only when you access Kotlin class from Java code that needs a static or code generation. You do not need to add it until you face a problem.Anarchist

© 2022 - 2024 — McMap. All rights reserved.