Kotlin init

If you observe the definition of primary constructor, there is no provision in the header to include some lines code for the primary constructor, except for the declaration of type variables. To fill this void, there is init block. But, care has to be taken that init block is run when the class variable is initialized. Hence, this init block is run for all the constructors irrespective of primary and secondary, and after the execution of primary constructor block. Init block is run with the context of primary constructor.

An example Kotlin program to demonstrate the working of Kotlin init block is given below :

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

fun main(args:Array<String>){

varperson_0=Person("Ranjan",21)

person_0.printPersonDetails()

varperson_1=Person("Suresh",25,"Teaching")

person_1.printPersonDetails()

}

/**

* Kotlin Init Example

*/

classPerson constructor(varname:String,varage:Int){

varprofession:String="Not Mentioned"

// initializer block is run during the initialization of class object, after executing constructor

init{

println("$name's details are being held in this class object.")

}

constructor(name:String,age:Int,profession:String):this(name,age){

this.profession=profession

}

fun printPersonDetails(){

println("$name whose profession is $profession, is $age years old.")

}

}

1

2

3

4

5

6

Ranjan's details are being held in this class object.

Ranjan whose profession is Not Mentioned, is 21 years old.

Suresh'sdetails are being held inthisclassobject.

Suresh whose profession isTeaching,is25years old.

Conclusion :

In this Kotlin Tutorial, we have learnt the structure of a class in Kotlin with an example, also the types of Kotlin Constructors we have for a class : primary constructor and secondary constructor, and the role of init block in aiding primary constructor.