Kotlin 中的原始属性初始化
Primitive properties initialization in Kotlin
我有不可变的 Int
属性 值在 constructor.Something 中计算如下:
class MyClass {
val myProperty:Int
init{
//some calculations
myProperty=calculatedValue
}
}
但是这段代码不会 compile.Compiler 表示 Property must be initialized or be abstract
。我无法初始化它,因为它的值只有在 class instantiation.Looks 之后才知道,就像 kotlin forces我要 属性 mutable.Is 这是唯一的方法吗?
UPD:I 刚刚意识到我在 for
循环中分配了 属性 值,这导致 unable to reassign val property
error.This 主题是 deletion.Sorry.[=15= 的主题]
可接受的答案是使用 private setter:
class MyClass {
var myProperty:Int=0
private set
init{
//some calculations
myProperty=calculatedValue
}
}
但是仍然有可能在 class
中重新分配错误的值
为什么不在初始化的时候做呢?
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
}
}
我有不可变的 Int
属性 值在 constructor.Something 中计算如下:
class MyClass {
val myProperty:Int
init{
//some calculations
myProperty=calculatedValue
}
}
但是这段代码不会 compile.Compiler 表示 Property must be initialized or be abstract
。我无法初始化它,因为它的值只有在 class instantiation.Looks 之后才知道,就像 kotlin forces我要 属性 mutable.Is 这是唯一的方法吗?
UPD:I 刚刚意识到我在 for
循环中分配了 属性 值,这导致 unable to reassign val property
error.This 主题是 deletion.Sorry.[=15= 的主题]
可接受的答案是使用 private setter:
class MyClass {
var myProperty:Int=0
private set
init{
//some calculations
myProperty=calculatedValue
}
}
但是仍然有可能在 class
中重新分配错误的值为什么不在初始化的时候做呢?
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
}
}