【发布时间】:2017-12-04 00:45:57
【问题描述】:
我正在从 Java 切换到 kotlin 以进行 Android 开发。当我在 Kotlin 中搜索等效的 Java 静态方法时,我发现伴生对象是。但问题是在 kotlin 中创建多个静态方法时。我收到这些错误,每个类只允许一个伴生对象。
【问题讨论】:
标签: android kotlin static-methods
我正在从 Java 切换到 kotlin 以进行 Android 开发。当我在 Kotlin 中搜索等效的 Java 静态方法时,我发现伴生对象是。但问题是在 kotlin 中创建多个静态方法时。我收到这些错误,每个类只允许一个伴生对象。
【问题讨论】:
标签: android kotlin static-methods
您可以在object 中放置多个方法和属性。它们就像类一样,但只有一个实例。
class A {
companion object {
fun a() {}
fun b() {}
val x = 42
var y = "foo"
}
}
【讨论】:
如果可以设置为
class C {
companion object {
@JvmStatic fun foo() {}
fun bar() {}
}
}
【讨论】:
If you use this annotation, the compiler will generate both a static method in the enclosing class of the object and an instance method in the object itself
@JvmStatic 的方法在Java 中可以调用为ClassName.methodName(),而在伴随对象中没有@JvmStatic 的方法在Java 中必须调用为ClassName.Companion.methodName() .如果您只使用 Kotlin,完全没有 Java,则没有区别。对于成员字段(变量),同样适用于带有 @JvmField 注释的字段。
@JvmField 是相关的。那是为了指示kotlin不要生成getter/setter。 @JvmStatic 仍可用于字段以使它们真正静态。此外,我认为没有注释的 Companions 表现为单例,这与真正的静态函数不同,即使它看起来只是语法更改。
您可以在**campanion 对象中放置一个或多个方法和变量** 让我们看下面的示例
class DialogClass {
companion object {
fun DialogMethod(context: Context) {
val dialog = Dialog(context)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(R.layout.activity_main)
dialog.show()
}
fun AnotherMethod() {
// Implement own logic here.
}
}
}
【讨论】: