0

Type 1:

class TestExample {
      object Bell {
       fun  add(){

       }
   }

 Class B{
  TestExample.Bell.add()
}

Type 2:

class TestExample {
      companion object Bell {
       fun  add(){

       }
   }



Class B{
TestExample.add()
 }

In this type 1 and type 2, which is static example and which is singleton example? Both behaves similar behavior right?

AlexTa
  • 5,133
  • 3
  • 29
  • 46
Star
  • 735
  • 3
  • 13
  • 34
  • probably duplicated: https://stackoverflow.com/questions/43814616/kotlin-difference-between-object-and-companion-object-in-a-class – Shermano Jun 26 '19 at 14:06
  • Also, learn how to read the bytecode, and therefore observe the differences between each: https://stackoverflow.com/a/35538539/2684 – Martin Marconcini Jun 26 '19 at 14:09

1 Answers1

3

From official Kotlin docs:

Object declarations

If you need a singleton - a class that only has got one instance - you can declare the class in the usual way, but use the object keyword instead of class

Companion objects

If you need a function or a property to be tied to a class rather than to instances of it (similar to @staticmethod in Python), you can declare it inside a companion object

AlexTa
  • 5,133
  • 3
  • 29
  • 46