title: how to access companion object from object instance in kotlin?
body: <p>Simple sample class with companion object</p>
  <pre class="lang-kt prettyprint-override"><code>class MyClass {
    companion object {
       val test = 25
    }
  }
  </code></pre>
  <p>The value test can be accessed from by <code>MyClass.test</code>, but how to access from an
  instance of MyClass?  If I have <code>val sample = MyClass()</code>,  how do I then access test from sample?  <code>sample::class.test</code> is not correct....is there a way?</p>
  <p>The question has been raised:  'Why not simply use MyClass.test'?</p>
  <p>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?</p>
  <p>Consider when working with an object passed as a more abstract base class, with several classes possible for the object you are working with.</p>
  <p>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.</p>
  <p>My solution so far is to simply implement the equivalent of MyClass in with test as a static</p>
  <pre class="lang-java prettyprint-override"><code>public class MyClass {
      static Integer test = 25;
      public Integer testGetter(){ return test; }    
  }
  </code></pre>
  <p>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.</p>
  <p>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.</p>