Star
Star

Reputation: 707

Which is static and which is singleton in kotlin?

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?

Upvotes: 0

Views: 358

Answers (1)

AlexTa
AlexTa

Reputation: 5251

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

Upvotes: 3

Related Questions