Search code examples
kotlininitialization

Primitive properties initialization in Kotlin


I have immutable Int property which value is caclulated in the constructor.Something like this:

class MyClass {
    val myProperty:Int
    init{
        //some calculations
        myProperty=calculatedValue
    }
}

But this code won't compile.Compiler says Property must be initialized or be abstract.I can't initialize it as it's value will be known only after class instantiation.Looks like kotlin forces me to have the property mutable.Is this the only way?
UPD:I just realized I was assigning property value inside for loop which leads to unable to reassign val property error.This topic is subject for deletion.Sorry.


Solution

  • Why not doing it while initialization?

    class MyClass {
        val myProperty: Int = calcMyProperty() // use that if the calculation is complex
        val myOtherProperty: Int = 5 + 3 // use that if the calculation is simple
    
        private fun calcMyProperty(): Int {
            // some very complex calculation
            return 5 + 3
        }
    }