What’s wrong with that code?

Technology CommunityCategory: KotlinWhat’s wrong with that code?
VietMX Staff asked 3 years ago
Problem

Let’s say I want to override the Int getter so that it returns 0 if the value negative for the data class. What’s bad with that approach?

data class Test(private val _value: Int) {
  val value: Int
    get() = if (_value < 0) 0 else _value
}

The problem with this approach is that data classes aren’t really meant for altering data like this. They are really just for holding data. Overriding the getter for a data class like this would mean that Test(0) and Test(-1) wouldn’t equal one another and would have different hashCodes, but when you called .value, they would have the same result. This is inconsistent, and while it may work for you, other people on your team who see this is a data class, may accidentally misuse it.