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.
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
}
}
You can use the run
function. You val
will be initialized with the value that is returned from the lambda (the last expression). Like this:
class MyClass {
val myProperty: Int = run {
//some calculations
calculatedValue
}
}
The acceptable answer is to use private setter:
class MyClass {
var myProperty:Int=0
private set
init{
//some calculations
myProperty=calculatedValue
}
}
However there is still chance to reassign wrong value inside the class
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.