How to access Kotlin companion object in Java?

前端 未结 4 1524
谎友^
谎友^ 2021-01-07 15:58

I convert one of my Java class to Kotlin and the class as below.

class MainApplication : Application() {
    companion object {
        operator fun get(cont         


        
4条回答
  •  走了就别回头了
    2021-01-07 16:32

    By omitting the name of your companion object, the name Companion must be used to access the methods.

    Example:

    class MyClass1 {
        companion object Object1 {
            fun method1 {
            }
        }
    }
    
    class MyClass2 {
        companion object {
            fun method2 {
            }
        }
    }
    

    To invoke the first companion object method you would do the following:

    MyClass1.method1()
    

    To invoke the second:

    MyClass2.Companion.method2()
    

    See the Kotlin docs on Companion Objects for details.

提交回复
热议问题