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

KotlinConstructorInitialization Block

Kotlin Problem Overview


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")
     }    
}

Kotlin Solutions


Solution 1 - Kotlin

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".

Solution 2 - Kotlin

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.

Solution 3 - Kotlin

Since,

> The primary constructor cannot contain any code.

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

init blocks allow adding code to the primary constructor.

Solution 4 - 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamir BhattView Question on Stackoverflow
Solution 1 - Kotlindeepak rajView Answer on Stackoverflow
Solution 2 - KotlinEugene PetrenkoView Answer on Stackoverflow
Solution 3 - KotlinJenView Answer on Stackoverflow
Solution 4 - KotlinKKHView Answer on Stackoverflow