Why do we use “companion object” as a kind of replacement for Java static fields in Kotlin?

前端 未结 4 1519
鱼传尺愫
鱼传尺愫 2020-11-29 19:23

What is the intended meaning of \"companion object\"? So far I have been using it just to replace Java\'s static when I need it.

I am confused with:

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 19:45

    Why is it called "companion"?

    An object declaration inside a class can be marked with the companion keyword:

    class MyClass {
        companion object Factory {
            fun create(): MyClass = MyClass()
        }
    }
    

    Members of the companion object can be called by using simply the class name as the qualifier:

    val instance = MyClass.create()
    

    If you only use 'object' without 'companion', you have to do like this:

    val instance = MyClass.Factory.create()
    

    In my understanding, 'companion' means this object is companion with the outter class.

提交回复
热议问题