Regarding getters and setters, I was implementing a class property that counts how many times it was accessed. Here’s my starting code for that:
class AccessCounter {
var count: Int = RESET_VALUE // 0
get() = ++field
// Setter in the next step
}
Now, I’d like to be able to set it according to various options like “RESET”, “MID”, “MAX”, and so on. Here’s what that would look like (gives an error):
class AccessCounter {
var count: Int = RESET_VALUE // 0
get() = ++field
set(v: String) { // Error (new feature)
when(v) {
"RESET" -> field = RESET_VALUE
"MID" -> field = MID_VALUE // Some Int value
"MAX" -> field = MAX_VALUE // Some Int value
// And so on
}
}
}
fun main() {
val ac = AccessCounter()
// Some code here which gets the counter multiple times (thus adding to it the number of times it was accessed)
println(ac.count) // Returns an Int with the number of times count was accessed (including this time)
ac.count = "RESET" // Error (new feature)
}
The problem with this is that “RESET” is a String, and only Ints can be passed to the setter parameter, since count is an Int.
Would it be possible to have a setter parameter of a type other than the property type, like in this case? If we don’t specify the type, Kotlin infers the property type like it does so far (to Int in this case), but if we specify another type it still accepts it (the field would still be updated to the property type, like in the example above).
Extra
There’s of course a turnaround in which we can pass integers to the setter, each corresponding to a specific String option (like below), but maybe this could be avoided:
class AccessCounter {
var count: Int = RESET_VALUE // 0
get() = ++field
set(v) {
when(v) {
0 -> field = RESET_VALUE
1 -> field = MID_VALUE // Some Int value
2 -> field = MAX_VALUE // Some Int value
// And so on
}
}
}
fun main() {
val ac = AccessCounter()
// Some code
ac.count = 1 // MID_VALUE
// Some code
ac.count = 0 // RESET_VALUE
}
Thank you for your attention and support!
*Also, happy new year!