在Kotlin中没有静态关键字。

在Kotlin中表示静态Java方法的最佳方法是什么?


当前回答

简单来说,你可以使用“同伴对象”进入Kotlin静态世界,比如:

  companion object {
    const val TAG = "tHomeFragment"
    fun newInstance() = HomeFragment()
}

要创建一个常量字段,请使用代码中的“const val”。 但是尽量避免使用静态类,因为它会给使用Mockito进行单元测试带来困难。

其他回答

在kotlin中没有静态关键字。如果你想遵循DRY, kotlin文档建议使用包级函数。 创建一个扩展名为.kt的文件,并将您的方法放在其中。

package p
    fun m(){
    //fun body
    }

编译后m将会有一个public static final void的签名

and

import p.m

所有静态成员和函数都应该在伴生块中

  companion object {
    @JvmStatic
    fun main(args: Array<String>) {
    }

    fun staticMethod() {
    }
  }

如果你需要一个函数或属性绑定到一个类,而不是它的实例,你可以在一个伴随对象中声明它:

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)

很多人提到伴生对象,这是正确的。但是,正如你所知道的,你也可以使用任何类型的对象(使用对象关键字,而不是类),即,

object StringUtils {
    fun toUpper(s: String) : String { ... }
}

像使用java中的静态方法一样使用它:

StringUtils.toUpper("foobar")

That sort of pattern is kind of useless in Kotlin though, one of its strengths is that it gets rid of the need for classes filled with static methods. It is more appropriate to utilize global, extension and/or local functions instead, depending on your use case. Where I work we often define global extension functions in a separate, flat file with the naming convention: [className]Extensions.kt i.e., FooExtensions.kt. But more typically we write functions where they are needed inside their operating class or object.

object objectName {
    fun funName() {

    }
}