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:
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.
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()
OUTER_TAG
in companion gives error because it is a class variable. You cannot access it without an instance. – Anarchist