1

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

1 Answers1

4

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.

Egor
  • 39,695
  • 10
  • 113
  • 130
  • 1
    Thank you, I was thinking that because by accessing A, actually a get Method is called, that the x * y was recomputed every time too – Marios Plenchidis Sep 18 '22 at 20:21
  • 2
    Doesn’t A compile to use a backing field (so it uses more memory) and B evaluate the multiplication every time it’s accessed (so it uses more CPU)? By usually trivial amounts (which might not be trivial at scale), but I wouldn’t call that exactly the same. – Tenfour04 Sep 19 '22 at 01:35
  • @Tenfour04, valid point. Guess we should've defined what "exactly the same" means first. – Egor Sep 19 '22 at 10:56