Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Confusion about fileds and get methods in Kotlin

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading