Override getter for Kotlin data class

前端 未结 7 725
长发绾君心
长发绾君心 2020-12-04 17:28

Given the following Kotlin class:

data class Test(val value: Int)

How would I override the Int getter so that it returns 0 if

7条回答
  •  佛祖请我去吃肉
    2020-12-04 17:52

    I found the following to be the best approach to achieve what you need without breaking equals and hashCode:

    data class TestData(private var _value: Int) {
        init {
            _value = if (_value < 0) 0 else _value
        }
    
        val value: Int
            get() = _value
    }
    
    // Test value
    assert(1 == TestData(1).value)
    assert(0 == TestData(-1).value)
    assert(0 == TestData(0).value)
    
    // Test copy()
    assert(0 == TestData(-1).copy().value)
    assert(0 == TestData(1).copy(-1).value)
    assert(1 == TestData(-1).copy(1).value)
    
    // Test toString()
    assert("TestData(_value=1)" == TestData(1).toString())
    assert("TestData(_value=0)" == TestData(-1).toString())
    assert("TestData(_value=0)" == TestData(0).toString())
    assert(TestData(0).toString() == TestData(-1).toString())
    
    // Test equals
    assert(TestData(0) == TestData(-1))
    assert(TestData(0) == TestData(-1).copy())
    assert(TestData(0) == TestData(1).copy(-1))
    assert(TestData(1) == TestData(-1).copy(1))
    
    // Test hashCode()
    assert(TestData(0).hashCode() == TestData(-1).hashCode())
    assert(TestData(1).hashCode() != TestData(-1).hashCode())
    

    However,

    First, note that _value is var, not val, but on the other hand, since it's private and data classes cannot be inherited from, it's fairly easy to make sure that it is not modified within the class.

    Second, toString() produces a slightly different result than it would if _value was named value, but it's consistent and TestData(0).toString() == TestData(-1).toString().

提交回复
热议问题