問題描述
Kotlin中沒有static關鍵字,也就是沒有直接定義靜態函數/靜態方法的static關鍵字。那麽用Kotlin表示類似JAVA的static靜態方法的方式是?
最佳回答
將函數放在”companion object”中。
所以像這樣的java代碼:
class Foo {
public static int a() { return 1; }
}
會變成
class Foo {
companion object {
fun a() : Int = 1
}
}
然後,您可以從Kotlin代碼內部使用它,如下所示:
Foo.a();
但是從Java代碼中,您需要將其寫作
Foo.Companion.a();
(注:上麵這個寫法在Kotlin中也有效。)
如果您不想指定Companion位,則可以添加@JvmStatic批注或命名您的Companion類。
根據docs:
Companion Objects
An object declaration inside a class can be marked with the companion keyword:
class MyClass { companion object Factory { fun create(): MyClass = MyClass() } }Members of the companion object can be called by using simply the class name as the qualifier:
val instance = MyClass.create()…
However, on the JVM you can have members of companion objects generated as real static methods and fields, if you use the
@JvmStaticannotation. See the Java interoperability section for more details.
添加@JvmStatic批注看起來像這樣
class Foo {
companion object {
@JvmStatic
fun a() : Int = 1;
}
}
然後它將作為一個真正的Java靜態函數存在,可以從Java和Kotlin中以Foo.a()的形式進行訪問。
如果隻是不喜歡Companion名稱,則還可以為伴隨對象提供一個明確的名稱,如下所示:
class Foo {
companion object Blah {
fun a() : Int = 1;
}
}
它可以讓您以相同的方式從Kotlin調用它。在JAVA中可以用Foo.Blah.a()在Java中調用它(這個調用方法在Kotlin中也可以使用)。
第二種回答
A.舊的Java方式:
- 聲明
companion object以包含靜態方法/變量class Foo{ companion object { fun foo() = println("Foo") val bar ="bar" } } - 調用 :
Foo.foo() // Outputs Foo println(Foo.bar) // Outputs bar
B.新的Kotlin(科特林)方式
- 直接在文件上聲明,而無需在
.kt文件上聲明類。fun foo() = println("Foo") val bar ="bar" - 使用
methods/variables及其名稱。 (導入後)采用 :foo() // Outputs Foo println(bar) // Outputs bar
參考資料

