Initialise val in Kotlin from a method in init block

Viewed 508

Let's have class as follows:

class TestClass()  {
    val isInitialised : Boolean

    init {
        isInitialised = true
    }
}

Val isInitialised has its initialisation in the init block and the compiler is happy. Once I have more val members I would like to group their initialisation to a method and call the method from the init block, like:

class TestClass()  {
    val isInitialised : Boolean

    init {
        setInitValue()
    }
    
    private fun setInitValue() {
        isInitialised = true
    }
}

In the second case I receive errors while building: Property must be initialized or be abstract and Val cannot be reassigned.

Is there a way to use methods within init block to initialise val members of a class?

1 Answers

No, but you can have multiple init blocks, each corresponding to a method you would use.

Alternately, you could make the properties lateinit var, but then

  1. it's a var, not a val;
  2. it's easy not to initialize it by accident.
Related