https://kotlinlang.org logo
Title
o

ossama

07/04/2017, 1:08 PM
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

agomez

07/04/2017, 1:11 PM
ossama: i guess they are instance members of the companion object which is a singleton
e

evanchooly

07/04/2017, 1:26 PM
right
e

elizarov

07/04/2017, 1:32 PM
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

poohbar

07/04/2017, 1:37 PM
@elizarov So why is there a need for
@JvmStatic
then?
e

evanchooly

07/04/2017, 1:37 PM
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

poohbar

07/04/2017, 1:40 PM
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

evanchooly

07/04/2017, 1:41 PM
that's not been my experience using companion object fields via java
e

elizarov

07/04/2017, 2:32 PM
@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

evanchooly

07/04/2017, 2:33 PM
iirc, you can put
@JvmStatic
on the companion object itself to expose them all as static fields on the parent
p

poohbar

07/04/2017, 2:34 PM
ohh.. I think I get it now. Thanks