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") } }
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...
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.
A Kotlin class can have following two type of constructors: Primary Constructor. Second Constructors.
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).
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With