How would you override default getter for Kotlin data class?

Technology CommunityCategory: KotlinHow would you override default getter for Kotlin data class?
VietMX Staff asked 3 years ago
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?

  1. 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.
  2. Don’t use a data class. Use a regular class.
    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()
       }
    }
  3. 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
    }