[英]Primitive properties initialization in Kotlin
我有一個不變的Int
屬性,該值在構造函數中計算出來。
class MyClass {
val myProperty:Int
init{
//some calculations
myProperty=calculatedValue
}
}
但是這段代碼不會被編譯。編譯器說Property must be initialized or be abstract
。我無法初始化它,因為它的值只有在類實例化之后才能知道。像是Kotlin迫使我將屬性變為可變的,這是唯一的方式?
UPD:我剛剛意識到我在for
循環內分配了屬性值,導致unable to reassign val property
主題值得刪除。
為什么在初始化時不這樣做?
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
}
}
您可以使用run
功能。 您的val
將使用從lambda(最后一個表達式)返回的值進行初始化。 像這樣:
class MyClass {
val myProperty: Int = run {
//some calculations
calculatedValue
}
}
可接受的答案是使用私有設置器:
class MyClass {
var myProperty:Int=0
private set
init{
//some calculations
myProperty=calculatedValue
}
}
但是,仍然有機會在班級內部重新分配錯誤的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.