Kotlin basics: object

“A bicycle leaning against a white wall.” by Ruslan Bardash on Unsplash
  • Defines a class
  • Creates an instance of that class

Object declarations (singletons)

Companion objects

  • Accessing members of companion objects don’t need a name. To access the companion object just use the class name. Like in object declarations
  • Companion objects are initialized when the corresponding class is loaded, on the other hand object declarations are lazily initialized, when accessed for the first time.

Companion objects as factory methods

  • They can be named accordingly with their purpose.
  • The returned object can be a subclass of the class where it is declared.
  • They can return old objects instead of creating new ones.

Companion objects and extension functions

Companion objects implementing an interface

Object expressions

  • Can implement more than one interface.
  • Can access and modify non-final variables from the function where it is created.
  • Are created every time they are executed. They aren’t singletons like object declarations.



Android-Kotlin Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store