I had a widget and it’s style need to initialize. Here’s my code with simplification.
class Style() {
var width = 0.0
var height = 0.0
var name = ""
}
class Widget(val name: String, val width: Double) {
val style: Style
init {
val height = width * 1.5
style = Style().apply {
width = width
// height = height got a compile error here:Val cannot be reassigned
name = name
}
}
}
I tried to fix it :
class Widget(name: String, width: Double) {
val style: Style
init {
val height = width * 1.5
style = Style().apply {
// width = width got a compile error here:Val cannot be reassigned
// height = height got a compile error here:Val cannot be reassigned
// name = name got a compile error here:Val cannot be reassigned
}
}
}
Even worse, I tried this:
class Widget(val name: String,val width: Double) {
val style: Style
init {
val height = width * 1.5
style = Style().apply {
this.width = width
this.height = height
this.name = name
}
}
}
When I called
val widget = Widget("Button", 12.0)
with(widget.style){
println("$name, $width, $height")
}
But result was: , 0.0, 18.0
Finally I tried:
class Widget(name: String, width: Double) {
val style: Style
init {
val height = width * 1.5
style = Style().apply {
this.width = width
this.height = height
this.name = name
}
}
}
I got the right answer: Button, 12.0, 18.0
I was confused.
Why?