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

前端 未结 4 1486
鱼传尺愫
鱼传尺愫 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 20:00

    We can say that companion is same as "Static Block" like Java, But in case of Kotlin there is no Static Block concept, than companion comes into the frame.

    How to define a companion block:

    class Example {
          companion object {
            fun display(){
            //place your code
         }
      }
    }
    

    Calling method of companion block, direct with class name

    Example.Companion.display
    

提交回复
热议问题