简体   繁体   English

Kotlin中每个类只允许一个伴随对象

[英]only one companion object is allowed per class in Kotlin

I was switching from Java to kotlin for Android Devlopment. 我正在从Java转换为kotlin for Android Devlopment。 When I searched about equivalent of Java static methods in Kotlin, I found that companion object is. 当我在Kotlin中搜索相当于Java静态方法时,我发现伴随对象是。 But the problem is while creating more than one static methods in kotlin. 但问题是在kotlin中创建多个静态方法。 I get these errors only one companion object is allowed per class. 我得到这些错误,每个类只允许一个伴随对象。

You can put multiple methods and properties inside an object . 您可以在对象中放置多个方法和属性。 They're just like classes, but they have a single instance. 它们就像类,但它们只有一个实例。

class A {
    companion object {
        fun a() {}
        fun b() {}

        val x = 42
        var y = "foo"
    }
}

If you can set it as 如果你可以设置为

class C {
    companion object {
        @JvmStatic fun foo() {}
        fun bar() {}
    }
}

See this link for static method 有关静态方法,请参阅此链接

You can put one or more than one methods and variables inside **campanion object ** Let see example below 你可以在** 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.
    }
    }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM