简体   繁体   中英

companion object are overused in Kotlin?

Here I have java code

  private static void content() {}

and I convert to Kotlin it shows it becomes

companion object {

    private fun content() {}
}

I am wondering should I keep it in companion object or should I remove companion object?

The companion object is a singleton, and its members can be accessed directly via the name of the containing class (although you can also insert the name of the companion object if you want to be explicit about accessing the companion object)

A companion object is initialized when the class is loaded (typically the first time it's referenced by other code that is being executed), in a thread-safe manner. You can omit the name, in which case the name defaults to Companion. A class can only have one companion object, and companion objects can not be nested.

class Car(val horsepowers: Int) {
companion object Factory {
    val cars = mutableListOf<Car>()

    fun makeCar(horsepowers: Int): Car {
        val car = Car(horsepowers)
        cars.add(car)
        return car
    }
}

}

val car = Car.makeCar(150)
println(Car.Factory.cars.size)

The advantage of companion objects have over static members is that they can inherit from other classes or implement interfaces and generally behave like any other singleton.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM