What is the equivalent of Java static methods in Kotlin?

前端 未结 28 1187
眼角桃花
眼角桃花 2020-11-27 09:03

There is no static keyword in Kotlin.

What is the best way to represent a static Java method in Kotlin?

28条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 09:43

    If you need a function or a property to be tied to a class rather than to instances of it, you can declare it inside a companion object:

    class Car(val horsepowers: Int) {
        companion object Factory {
            val cars = mutableListOf()
    
            fun makeCar(horsepowers: Int): Car {
                val car = Car(horsepowers)
                cars.add(car)
                return car
            }
        }
    }
    

    The companion object is a singleton, and its members can be accessed directly via the name of the containing class

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

提交回复
热议问题