Kotlin 中没有 static
关键字。
在 Kotlin 中表示 static
Java 方法的最佳方式是什么?
最佳答案
你把函数放在“伴生对象”中。
所以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
注释或命名您的伴随类。
来自 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
@JvmStatic
annotation. 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()
(也适用于 Kotlin)。
关于java - Kotlin 中的 Java 静态方法等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40352684/