/* * Getters and setters in Kotlin * getters are defined automatically for data classes * setters are also defined automatically for var types * for data classes * * getters and setters are NOT defined for regualar classes * but they can be written. * * Note that while the syntax is similar to that of Java * public vars, it is NOT the same as setting is always done through * get and set functions. Usually they are just not seen. * * @author gtowell * created: Oct 20. 2021 */ data class Dxy(var x:Int, val y:Int) { } fun doDataClass() { val dxy = Dxy(4,5) println(dxy) dxy.x = 8 println(dxy) //dxy.y=10 // does not compile, this is a val so no setter } fun main() { doDataClass() doClass() doExClass() } class Cxy(x:Int, y:Int) { var x:Int = x // this is sort of like overriding x, but the compile treats it as you would want get() = field*3 // "field" needed in getters and setters to avoid infinite recursion. //set(value) { field=value } // this is what the setter does anyway var y:Int = y set(value) {} // override the setter to do NOTHING } fun doClass() { val xy = Cxy(4,5) println(xy) println("Cxy xy.x = %d xy.y=%d".format(xy.x, xy.y)) xy.x = 8 xy.y = 42 println("Cxy xy.x = %d xy.y=%d".format(xy.x, xy.y)) //dxy.y=10 // does not compile, this is a val so no setter } class CCxy(var x:Int, val y:Int=1) fun CCxy.x() = this.x*2 fun CCxy.x(xx:Int):Unit { this.x = xx*2 } var hidden:Int=0 var CCxy.z: Int // this property is NOT really in CCxy, but it looks like it is get()=hidden set(zz) { hidden = zz} fun doExClass() { val xy = CCxy(4,5) println("CCxy x=%d y=%d z=%d".format(xy.x, xy.y, xy.z)) xy.x = 8 println("CCxy x=%d y=%d z=%d".format(xy.x, xy.y, xy.z)) xy.z=9 println("CCxy x=%d y=%d z=%d".format(xy.x, xy.y, xy.z)) }