Since A is a property and not a field, does that mean that A and B are functioning exactly the same way? If not, what are their difference?
class myClass(val x : Int, val y : Int){
val A = x * y
val B :Int
get(){
return x * y
}
}
CodePudding user response:
In this specific example, a property with a backing field (A
) and a property without a backing field (B
) work exactly the same, because x
and y
are val
s and their values can't be reassigned - no matter how many times you compute x * y
it'll always return the same result. But consider the following program:
class myClass(var x : Int, val y : Int){
val A = x * y
val B :Int
get(){
return x * y
}
}
fun main() {
val myClass = MyClass(x = 2, y = 3)
println(myClass.A) // 6
println(myClass.B) // 6
myClass.x = 4
println(myClass.A) // 6
println(myClass.B) // 12
}
x
is a var
now, which means that its value can be changed. The value of A
has already been computed when the instance of MyClass
was created, so changing the value of x
has no effect on the value of A
. But since accessing B
executes the body of its getter every time, a change in the value of x
will affect the result of the next call to that getter.