Kotlin: Difference between object and companion object in a class

后端 未结 6 1228
傲寒
傲寒 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:45

    Objects can implement interfaces. Inside a class, defining a simple object that doesn't implement any interfaces has no benefit in most cases. However, defining multiple objects that implement various interfaces (e.g. Comparator) can be very useful.

    In terms of lifecycle, there is no difference between a companion object and a named object declared in a class.

提交回复
热议问题