Error on the second println :
Smart cast to 'Boolean' is impossible, because 'r.isSquare' is a mutable property that could have been changed by this time
fun main(args: Array<String>) {
val r: Rectangle = Rectangle(5,5)
println(r.isSquare)
r.isSquare = true
println(r.isSquare) // error but works with println(r.isSquare?:false)
}
data class Rectangle(var height: Int, var width: Int){
var isSquare: Boolean? = null
}
If it was null, it would print null like the first println, why do i have to do this ?
Edit 2
Thanks for all your answers, what i understand now : First println is
println(message: Any?)
Second println is
println(message: Boolean)
Because r.isSquare = true make compiler trust that isSquare is Boolean and not anymore Boolean?
Edit2
Here is how i handle the compiler to keep trusting isSquare is Boolean?
fun main(args: Array<String>) {
val r: Rectangle = Rectangle(5, 5)
println(r.isSquare)
r.isSquare = true as Boolean? // if no cast, he will try wrong println signature
println(r.isSquare)
}
data class Rectangle(var height: Int, var width: Int){
var isSquare: Boolean? = null
}