Override getter for Kotlin data class

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

    This seems to be one (among other) annoying drawbacks of Kotlin.

    It seems that the only reasonable solution, which completely keeps backward compatibility of the class is to convert it into a regular class (not a "data" class), and implement by hand (with the aid of the IDE) the methods: hashCode(), equals(), toString(), copy() and componentN()

    class Data3(i: Int)
    {
        var i: Int = i
    
        override fun equals(other: Any?): Boolean
        {
            if (this === other) return true
            if (other?.javaClass != javaClass) return false
    
            other as Data3
    
            if (i != other.i) return false
    
            return true
        }
    
        override fun hashCode(): Int
        {
            return i
        }
    
        override fun toString(): String
        {
            return "Data3(i=$i)"
        }
    
        fun component1():Int = i
    
        fun copy(i: Int = this.i): Data3
        {
            return Data3(i)
        }
    
    }
    

提交回复
热议问题