What is the difference between init block and constructor in kotlin?
As stated in the Kotlin docs:
The primary constructor cannot contain any code. Initialization code can be placed in initializer blocks, which are prefixed with the
init
keyword.
During an instance initialization, the initializer blocks are executed in the same order as they appear in the class body, interleaved with the property initializers: ...
https://kotlinlang.org/docs/classes.html#constructors
A class in Kotlin class a primary constructor (the one after a class name) which does not contain code, it is only able to initialize properties (e.g. class X(var prop: String)
).
The init{..}
block in the place, where you can put more code that will run after properties are initialized:
initializer blocks are executed in the same order as they appear in the class body, interleaved with the property initializers
More about that is in https://kotlinlang.org/docs/reference/classes.html#constructors
Here is an example:
class X(var b: String) {
val a = print("a")
init {
print("b")
}
constructor() : this("aaa") {
print("c")
}
}
X()
When called it prints abc
. Thus the init{..}
in invoked after primary constructor but before a secondary one.
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"
.
Since,
The primary constructor cannot contain any code.
https://kotlinlang.org/docs/reference/classes.html
init blocks allow adding code to the primary constructor.