hi everyone, what is difference between companion ...
# getting-started
h
hi everyone, what is difference between companion object and object keyword? tks so much
j
companion object
is just an
object
inside a
class
.
1
v
Altho there can be objects inside a class that are not companion
h
Companion object also can reference to any thing in that class including private variable, …
v
No they can't
Companion objects and objects inside a class are almost the same for the exception the initialization order and jvm-static things
h
Companion object and object keyword are also replace "static" keyword (java), but I have not just see what difference between it, Can one clarify for me to be clear?
v
Note that
object
keyword can be used in other contexts too
1
object
creates a singleton, that's it. It is not directly related to
static
h
class AB { private val NAME = “name” companion object { fun print() { AB().NAME } } }
that code can build!
v
oh, nice, I did no know. The object does not have to be companion thou
h
about jvm-static, should u explain some about it? when do we use it?
h
@hqbao : object keyword will perform that feature class AB { private val NAME = “name” object { fun print() { AB().NAME } } }
i have not just see what difference
h
i dont know too, 😞
h
@voddan : "`object` creates a singleton, that's it. It is not directly related to `static`" ==> I think 'object' keyword in Kotlin will be replaced "static" keyword in Java
companion object Foo { const val count: Int = 2 var VALUES = arrayOf("X", "Y", "Z") } object Foo2 { var provider: String = "HAI" var xxx: Int= 0 const val count: Int = 2 } Both can be called from another context via AnotherClass.Foo and AnotherClass.Foo2
e
Companion object is an object that shares namespace with its containing class. You can refer to the members of companion object using the scope of the containing class both outside and inside of the class. In particular, it means, that inside the class you can refer to the
member
of companion object directly, without writing
Companion.member
and outside of the class you can write
Class.member
instead of
Class.Companion.member
.
1
stackoverflow 1
👍 3
h
@elizarov nice explaination