在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.

其他回答

你需要为静态方法传递同伴对象,因为kotlin没有静态关键字——同伴对象的成员可以通过简单地使用类名作为限定符来调用:

package xxx
    class ClassName {
              companion object {
                       fun helloWord(str: String): String {
                            return stringValue
                      }
              }
    }

对于Android使用从单个活动到所有必要活动的字符串。 就像java中的静态

public final static String TEA_NAME = "TEA_NAME";

Kotlin中的等效方法:

class MainActivity : AppCompatActivity() {
    companion object {
        const val TEA_NAME = "TEA_NAME"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

另一个需要价值的活动是:

val teaName = MainActivity.TEA_NAME

让,你有一个班级学生。你有一个静态方法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 Foo{
   fun foo() = println("Foo")
   val bar ="bar"  
}

Foo.INSTANCE.foo()

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

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.