Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between init block and constructor in kotlin?

I have started learning Kotlin. I would like to know the difference between init block and constructor. What is the difference between this and how we can use this to improve?

class Person constructor(var name: String, var age: Int) {     var profession: String = "test"      init {         println("Test")      }     } 
like image 483
Samir Bhatt Avatar asked Mar 26 '19 12:03

Samir Bhatt


People also ask

What is the difference between INIT and constructor?

The constructor is called by the container simply to create a POJO (plain old java object). init method is the method which is invoked when servlet in called and it adds values to the servlet context so its a very much difference between constructor and init method...

What are INIT block in Kotlin?

Kotlin initThe code inside the init block is the first to be executed when the class is instantiated. The init block is run every time the class is instantiated, with any kind of constructor as we shall see next. Multiple initializer blocks can be written in a class. They'll be executed sequentially as shown below.

What are the two types of constructors in Kotlin?

A Kotlin class can have following two type of constructors: Primary Constructor. Second Constructors.

How many INIT block does secondary constructor can have in Kotlin?

Moreover, we also have a secondary constructor that only accepts the person's last name. In addition to these two constructors, we're declaring two variables with property initializers based on the constructor inputs. Finally, we have two initializer blocks (blocks prefixed with the keyword init).


1 Answers

The init block will execute immediately after the primary constructor. Initializer blocks effectively become part of the primary constructor. The constructor is the secondary constructor. Delegation to the primary constructor happens as the first statement of a secondary constructor, so the code in all initializer blocks is executed before the secondary constructor body.

Example

class Sample(private var s : String) {     constructor(t: String, u: String) : this(t) {         this.s += u     }     init {         s += "B"     } } 

Think you initialized the Sample class with

Sample("T","U") 

You will get a string response at variable s as "TBU". Value "T" is assigned to s from the primary constructor of Sample class, and then immediately init block starts to execute it will add "B" to the variable. After init block secondary constructor block starts to execute and s will become "TBU".

like image 75
deepak raj Avatar answered Sep 23 '22 21:09

deepak raj