简体   繁体   中英

only one companion object is allowed per class in Kotlin

I was switching from Java to kotlin for Android Devlopment. When I searched about equivalent of Java static methods in Kotlin, I found that companion object is. But the problem is while creating more than one static methods in 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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