Problem
Given the following Kotlin class:
data class Test(val value: Int)
How would I override the Int getter so that it returns 0
if the value negative?
- Have your business logic that creates the data class alter the value to be 0 or greater before calling the constructor with the bad value. This is probably the best approach for most cases.
- Don’t use a
data class
. Use a regularclass
.class Test(value: Int) { val value: Int = value get() = if (field < 0) 0 else field override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Test) return false return true } override fun hashCode(): Int { return javaClass.hashCode() } }
- Create an additional safe property on the object that does what you want instead of having a private value that’s effectively overriden.
data class Test(val value: Int) { val safeValue: Int get() = if (value < 0) 0 else value }