Kotlin auto-generates it's getters and settings, but I never refer to them? Also, what is the correct way to write a custom getter/setter in Kotlin? When I say myObj.myVar = 99
I feel like myVar
is a public field of myObj
that I'm accessing directly? What is actually happening here?
In programming, getters are used for getting value of the property. Similarly, setters are used for setting value of the property. In Kotlin, getters and setters are optional and are auto-generated if you do not create them in your program.
Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.
1.0. interface Accessor<out V> Represents a property accessor, which is a get or set method declared alongside the property. See the Kotlin language documentation for more information.
This has been answered in a few places, but I thought that I would share a concrete example for people transitioning to Kotlin from Java/C#/C/C++, and who had the same question that I did:
I was having difficulty in understanding how getters and setters worked in Kotlin, especially as they were never explicitly called (as they are in Java). Because of this, I was feeling uncomfortable, as it looked like we were just directly referring to the vars/vals as fields. So I set out a little experiment to demonstrate that this is not the case, and that in fact it is the implicit (auto-generated) or explicit getter/setter that is called in Kotlin when you access a variable/value. The difference is, you don't explicitly ask for the default getter/setter.
From the documentation - the full syntax for declaring a property is:
var <propertyName>: <PropertyType> [= <property_initializer>]
[<getter>]
[<setter>]
And my example is
class modifiersEg {
/** this will not compile unless:
* - we assign a default here
* - init it in the (or all, if multiple) constructor
* - insert the lateinit keyword */
var someNum: Int?
var someStr0: String = "hello"
var someStr1: String = "hello"
get() = field // field is actually this.someStr1, and 'this' is your class/obj instance
set(value) { field = value }
// kotlin actually creates the same setters and getters for someStr0
// as we explicitly created for someStr1
var someStr2: String? = "inital val"
set(value) { field = "ignore you" }
var someStr3: String = "inital val"
get() = "you'll never know what this var actually contains"
init {
someNum = 0
println(someStr2) // should print "inital val"
someStr2 = "blah blah blah"
println(someStr2) // should print "ignore you"
println(someStr3) // should print "you'll never know what this var actually contains"
}
I hope that helps to bring it all together for some others?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With