在Kotlin中没有静态关键字。

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


当前回答

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

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.

其他回答

让,你有一个班级学生。你有一个静态方法getUniversityName()和一个静态字段totalStudent。

你应该在你的类中声明同伴对象块。

companion object {
 // define static method & field here.
}

然后你的类看起来像

    class Student(var name: String, var city: String, var rollNumber: Double = 0.0) {

    // use companion object structure
    companion object {

        // below method will work as static method
        fun getUniversityName(): String = "MBSTU"

        // below field will work as static field
        var totalStudent = 30
    }
}

然后你可以像这样使用那些静态方法和字段。

println("University : " + Student.getUniversityName() + ", Total Student: " + Student.totalStudent)
    // Output:
    // University : MBSTU, Total Student: 30
object objectName {
    fun funName() {

    }
}

kotlin文档提供了三种方法, 第一个是在包中定义函数,没有类:

package com.example

fun f() = 1

第二个是使用@JvmStatic注释:

package com.example

class A{
@JvmStatic
fun f() = 1
}

第三个是使用伴侣对象

package com.example

clss A{
companion object{
fun f() = 1
}
}

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

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.

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

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

    fun staticMethod() {
    }
  }