Override getter for Kotlin data class

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

    I know this is an old question but it seems nobody mentioned the possibility to make value private and writing custom getter like this:

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

    This should be perfectly valid as Kotlin will not generate default getter for private field.

    But otherwise I definitely agree with spierce7 that data classes are for holding data and you should avoid hardcoding "business" logic there.

提交回复
热议问题