Override getter for Kotlin data class

前端 未结 7 693
长发绾君心
长发绾君心 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:51

    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.

提交回复
热议问题