Reputation: 790
I ask myself why does Kotlin use companion objects instead of static methods and fields? Is it the reduce of boilerplate? I think it is easier to write companion object with all properties and functions inside curly braces instead of writing static every time. Here is an example.
class Hero {
companion object {
private var numberOfHeroes = 0
fun addNewHero() {
numberOfHeroes++
}
fun deleteHero() {
numberOfHeroes--
}
fun getAllHeroes(): Int {
return numberOfHeroes
}
}
init {
addNewHero()
}
}
fun main() {
val h1 = Hero()
val h2 = Hero()
print("Number of heros: ${Hero.getAllHeroes()}") // result is 2
}
But is this the only benefit? I know concisness is very important for Kotlin but I think there will be a little bit more.
Upvotes: 0
Views: 154
Reputation: 863
There is no benefit (or drawback, for that matter) for doing one or the other. It is just a language construct. And, frankly, you should ask what is the benefit of companion objects and extension functions vs static methods.
Java and most other OO languages chose to use static fields for the cases when there must only one instance of the field exist, and static methods for the cases when a) the instance of the class does not matter or is not important, or b) it actually kinda-does, but the developer writing a static method is not in control over the class, i.e. user wants to extend a functionality of the existing class, of which he/she is not the original author (provide a utility-function so to speak).
The example of the latter would be a utility method for the String
class that checks whether the string in question is blank (consists of only spaces or empty). The String
class cannot be altered directly by the end users, so a need to write a utility class with static method(s) arises. This task is perfectly addressed in Kotlin using extension functions and/or properties.
Upvotes: 1