Kotlin Object Declaration

In this tutorial you will learn about the Kotlin Object Declaration and its application with practical example.

Kotlin Object Declaration

In this article we are going to learn about Object Declaration(Singletons) & Object Expression .

Object Declaration: A class which have only one instance and follow object-oriented pattern called Singleton.

For an example suppose we are using SQL Database in our application as backend , You have created a class for database connection which you want to reuse same connection. For this you can create singletion class so that you can use same connection for every client.

For singleton class creation kotlin provide us object declaration feature, object keyword is used for this.

Syntax :-

In above code we can see that it combines Singleton class declaration and object declaration(single instance) of SingletonDemo classs.

Example: Let’s get understand this by an example. See below code and output.



Kotlin Object Expression

We can also use this object keyword to create objects of an anonymous class which is known as anonymous objects.Sometimes we need to create an object of a slight modification of some class, without explicitly declaring a new subclass for it, so here Kotlin provides us this concept with object expressions and object declarations.

You can see in below code that the an anonymous object is declared which extending MousAdapter class. There are two overrides methods mouseClicked() and mouseEntered() of MouseAdapter class. You can also assign a name of anonymous object and store it in a variable. Through below code .

Recommended:-  Kotlin do...while Loop

Example: Let’s understand it by an example, In this example we have stored anonymous object in variable, The variable name is w3adda which extends ExpressionDemo class and override learn() method.

Output: Let’s run this code you will get output like below image.


Example with class constructor: Let’s make one more example in which class has constructor and extended by anonymous object. See below code

Output: output of this code will look like below image.


In this tutorial we have learn about the Kotlin Object Declaration and its application with practical example. I hope you will like this tutorial.