Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 922
Rabindra Khadka Avatar asked Jun 30 '17 06:06

Rabindra Khadka


2 Answers

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"
    }
}
like image 70
zsmb13 Avatar answered Sep 24 '22 14:09

zsmb13


If you can set it as

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

See this link for static method

like image 33
N J Avatar answered Sep 24 '22 14:09

N J