Kotlin: Difference between object and companion object in a class

后端 未结 6 1264
傲寒
傲寒 2020-12-24 10:12

What is the difference between an object and a companion object in a class in kotlin?

Example:

class MyClass {

    object Holder {
        //somethi         


        
6条回答
  •  盖世英雄少女心
    2020-12-24 10:44

    A Companion object is initialized when the class is loaded (typically the first time it's referenced by other code that is being executed) whereas Object declarations are initialized lazily, when accessed for the first time.

    Please refer https://kotlinlang.org/docs/reference/object-declarations.html bottom section clearly defines the difference between these two.

提交回复
热议问题