37

Kotlin is known primarily as a drop-in replacement for Java, but it gets rid of a well-known Java construct: the static keyword. Instead, that class-level functionality is offered mainly by companion objects.

What is wrong with static methods and fields that companion objects provide a better alternative to? I'm confused about the rationale, and couldn't find any explanation in the documentation.

reevesy
  • 107
user1446
  • 492

3 Answers3

37

Scala also replaces class level declarations with a 'Singleton' object. The main advantage of this is that everything is an object. In Java, static members are treated very differently than object members. This means that you can't do things like implementing an interface or putting your class 'instance' into a map or pass it as a parameter to a method that takes Object. Companion objects allow for these things. That's the advantage.

JimmyJames supports Canada
  • 30,578
  • 3
  • 59
  • 108
18

Citing from the Kotlin reference docs:

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, and can, for example, implement interfaces.

Sounds very much to me like the Kotlin designers see this as an advantage over Java's static members.

Moreover, the part about Java interoperability and static members explains how companion objects can be used to create members which behave effectively like static members when annotated with @JvmStatic.

Doc Brown
  • 218,378
11

Kotlin is an object-oriented language. In an object-oriented language, something not being an object is an extremely crippling restriction. Classes aren't objects, but objects are objects (duh!), so the question should rather be: why would a language not use companion objects?

Another aspect is simplicity: why have two things, objects with instance members and classes with static members when you can just have objects with instance members?

An alternative that is used in many Smalltalk-derived languages, is to make classes themselves objects. E.g. in Smalltalk classes are instances of a parallel hierarchy of metaclasses. In Ruby, classes are instances of the Class class (and yes, that means that Class is an instance of itself). In that case, "class methods" are actually just normal instance methods of the class's metaclass. I don't know why this design wasn't chosen in Java (given its close to relation to Smalltalk), but it may have something to do with simplifying the type system (note that most languages with classes-as-objects tend to be dynamic languages).

Jörg W Mittag
  • 104,619