[SOLVED] Confusion about fileds and get methods in Kotlin

Issue

This Content is from Stack Overflow. Question asked by Marios Plenchidis

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
        }
}



Solution

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 vals 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.


This Question was asked in StackOverflow by Marios Plenchidis and Answered by Egor It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?