While reading about Companion objects, I’ve found ...
# announcements
o
While reading about Companion objects, I’ve found this Note that, even though the members of companion objects look like static members in other languages, at runtime those are still instance members of real objects Can you tell me, please, why they are used with different form then if they are instance members ?
a
ossama: i guess they are instance members of the companion object which is a singleton
e
right
e
This is not an entirely accurate depiction. While they appear to be instance members of real objects in Kotlin, then are represented on JVM as (translated to) static fields of the corresponding parent classes.
p
@elizarov So why is there a need for
@JvmStatic
then?
e
yes, there is.
otherwise, you have to resolve references to those fields via the
Companion
nested class.
if you don't use this stuff outside of kotlin, then don't bother with it.
p
But it makes no sense. Roman just said that the fields are actually represented as static fields on the corresponding parent class. So they should be directly accessible from within Java.
e
that's not been my experience using companion object fields via java
e
@poohbar They are
private
fields by default available only though accessor on the companion object. You cannot use
@JvmStatic
with companion object property, but you can use
@JvmField
, which makes the corresponding backing JVM fields
public
, so that they can be accessed from Java.
e
iirc, you can put
@JvmStatic
on the companion object itself to expose them all as static fields on the parent
p
ohh.. I think I get it now. Thanks