Why do we use “companion object” as a kind of replacement for Java static fields in Kotlin?

Technology CommunityCategory: KotlinWhy do we use “companion object” as a kind of replacement for Java static fields in Kotlin?
VietMX Staff asked 3 years ago

Because statics are not object-oriented. Kotlin does, however, have globals, which function similarly, and objects, which provide static functionality but remain object-oriented.

Java static part of a class can be elegantly expressed in terms of singleton: it’s a singleton object that can be called by the class’ name. Hence the naming: it’s an object that comes with a class.

Apart from naming, it is more powerful than Java static members: it can extend classes and interfaces, and you can reference and pass it around just like other objects.