Simple sample class with companion object
class MyClass {
companion object {
val test = 25
}
}
The value test can be accessed from by MyClass.test
, but how to access from an
instance of MyClass? If I have val sample = MyClass()
, how do I then access test from sample? sample::class.test
is not correct....is there a way?
The question has been raised: 'Why not simply use MyClass.test'?
I prefer to keep the question to 'how' rather than 'why', but since it has been asked I will try the 'why'. The same could also apply to the methods. Why not have static functions in a class and simply call Class.function() and pass the object as one of the parameters?
Consider when working with an object passed as a more abstract base class, with several classes possible for the object you are working with.
You could make a switch and for each possbile class and access the value (or function) from the appropriate class that way, but the idea of polymorphism is that you should be able to access class attributes like a method (even though a function method code for for all members of the same class) or a value common to all members of the class from an instance of an object of that class.
My solution so far is to simply implement the equivalent of MyClass in with test as a static
public class MyClass {
static Integer test = 25;
public Integer testGetter(){ return test; }
}
There are easy solutions to this in Java, C++, python etc.... (I will provide code samples for each is that helps) and i would think there will be a better solution in kotlin than resorting to using Java.
The kotlin companion object provides an alternative (and with advantages) to the static for situations where class attributes are accessed without an object instance (like factories), but there is another use of static for cases where although an object instance may be available, a static is appropriate since a single attribute can be shared by all members of the class and the attribute is not instance dependant.
Using reflection, you can go via companionObject
:
sample::class.companionObject?.memberProperties?.find { it.name == "test" }