This article explores different ways to initialize an object in Kotlin.

1. Using Class Constructor

The standard way to initialize an object in Kotlin is with the class constructor. It can accept a set of parameters to initialize its fields, or it can be parameterless. Kotlin has a concise syntax for declaring properties and initializing them:

Download Code

2. Using Copy Constructor

The copy constructor is a special constructor for creating a new object from another object. It takes a single argument, which should be another instance of the same class. You can explicitly invoke another constructor within the copy constructor with the this() function.

Download Code

3. Properties

Another alternative is to get an instance of the class using the default constructor and set its properties later.

Download Code

4. Using Anonymous Inner class

Although not recommended, you can use “Double Brace Initialization” to initialize the object. This creates an anonymous inner class with just an instance initializer in it.

Download Code

That’s all about initializing an object in Kotlin.