Given the following Kotlin class:
data class Test(val value: Int)
How would I override the Int
getter so that it returns 0 if
You could try something like this:
data class Test(private val _value: Int) {
val value = _value
get(): Int {
return if (field < 0) 0 else field
}
}
assert(1 == Test(1).value)
assert(0 == Test(0).value)
assert(0 == Test(-1).value)
assert(1 == Test(1)._value) // Fail because _value is private
assert(0 == Test(0)._value) // Fail because _value is private
assert(0 == Test(-1)._value) // Fail because _value is private
In a data class you must to mark the primary constructor's parameters with either val
or var
.
I'm assigning the value of _value
to value
in order to use the desired name for the property.
I defined a custom accessor for the property with the logic you described.