130

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")
     }    
}
jose praveen
  • 1,298
  • 2
  • 10
  • 17
Samir Bhatt
  • 3,041
  • 2
  • 25
  • 39
  • 3
    Do check this : https://kotlinlang.org/docs/reference/classes.html – Naimish Vinchhi Mar 26 '19 at 12:20
  • 2
    checkout this [init-blocks kotlin vs Java](https://chetangupta.net/init-blocks/) I explained what is init block and how its invoked order plus how it's different from Java's init block – Chetan Gupta Jan 26 '21 at 06:20

4 Answers4

225

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) {
    init {
        s += "B"
    }
    constructor(t: String, u: String) : this(t) {
        this.s += u
    }
}

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.
Then immediately the init block starts to execute; it will add "B" to the s variable.
Next it is the secondary constructor turn; now "U" is added to the s variable to become "TBU".

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
deepak raj
  • 3,331
  • 1
  • 12
  • 20
33

Since,

The primary constructor cannot contain any code.

https://kotlinlang.org/docs/reference/classes.html

the init{..} blocks allow adding code to the primary constructor.

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Jen
  • 459
  • 5
  • 5
22

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.

Eugene Petrenko
  • 4,874
  • 27
  • 36
  • So, if we have a secondary constructor, init block will call the first or secondary constructor? We can not initialize values in primary constructor. right? – Samir Bhatt Mar 26 '19 at 12:20
  • Thanks, I've added an example in the answer – Eugene Petrenko Mar 26 '19 at 12:29
  • 1
    "where you can put more code that will run _after_ properties are initialized" That's not correct. Actually "initializer blocks are executed in the same order as they appear in the class body, _interleaved_ with the property initializers". To see the difference, move `val a` after the `init` block. – Alexey Romanov Mar 27 '19 at 07:50
  • what happens to the `this("aaa")` after the secondary constructor's initializer is called. why doesn't `a = "aaa" `? – Kyle Angelo Gonzales Jul 11 '23 at 15:11
2

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

KKH
  • 81
  • 1
  • 8