init in kotlin
The init
keyword in Kotlin is used to define the primary constructor of a class or the initialization block of a class. It is executed when an instance of the class is created.
Here are the steps to use init
in Kotlin:
Step 1: Declare a class
To use the init
keyword, first, we need to declare a class. This can be done using the class
keyword followed by the class name.
Step 2: Declare the primary constructor After declaring the class, we need to declare the primary constructor. This is done inside the parentheses after the class name.
Step 3: Initialize properties
Inside the primary constructor, you can declare properties and initialize them if needed. Properties are declared using the val
or var
keyword followed by the property name and type.
Step 4: Define the init
block
After declaring the properties, you can define the init
block. This block is executed when an instance of the class is created. It is defined using the init
keyword followed by curly braces {}
.
Step 5: Write initialization code
Inside the init
block, you can write code to initialize the properties or perform any other required initialization tasks. You can access the properties of the class using the this
keyword.
Step 6: Create an instance of the class
Finally, you can create an instance of the class by calling the class name followed by parentheses ()
.
That's it! The init
block will be executed when the instance of the class is created, allowing you to perform any necessary initialization tasks.