

They also specify an object implementation and generate a type. Object declaration and object expression both creates a single object (although object declaration creates it lazily), but they are much more then just objects. More about object expression can be found on Kotlin reference. Here is an example of an object declaration: object HttpService ) Because of that, I hear often that programmers are erroneously using the object term to describe two other constructs: This causes some confusion in the programming community. The problem is that Kotlin introduced an object as a keyword. Singleton, on the other hand, is a pattern where you have just a single instance of class across its entire lifetime.In previous part, we’ve already described what is an object.

This is common across all instances of the class.

Q #2) Is Companion Object Singleton Kotlin?Īnswer: Companion object is not a Singleton object or Pattern in Kotlin – It’s primarily used to define class level variables and methods called static variables. These are also referred to as class level variables.

Primarily used for providing Singleton behavior.Ĭompanion objects are used as static equivalents in other languages. Objects are instantiated when they are called.Ĭompanion objects are instantiated as soon as the containing class is initialized. Q #1) What is the difference between – object and companion object in Kotlin?Īnswer: Companion objects are similar to objects, but they have a lot of differences.Ĭompanion objects need to be necessarily defined in another class. In other words, the function createConnection is acting like a FACTORY for creating objects of the type DatabaseConneciton. So, above, we are essentially creating an object of the type DatabaseConnection using the static method createConnection declared inside the companion object block.
