Override getter for Kotlin data class

前端 未结 7 695
长发绾君心
长发绾君心 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条回答
  • I have seen your answer, I agree that data classes are meant for holding data only, but sometimes we need to make somethings out of them.

    Here is what i'm doing with my data class, I changed some properties from val to var, and overid them in the constructor.

    like so:

    data class Recording(
        val id: Int = 0,
        val createdAt: Date = Date(),
        val path: String,
        val deleted: Boolean = false,
        var fileName: String = "",
        val duration: Int = 0,
        var format: String = " "
    ) {
        init {
            if (fileName.isEmpty())
                fileName = path.substring(path.lastIndexOf('\\'))
    
            if (format.isEmpty())
                format = path.substring(path.lastIndexOf('.'))
    
        }
    
    
        fun asEntity(): rc {
            return rc(id, createdAt, path, deleted, fileName, duration, format)
        }
    }
    
    0 讨论(0)
提交回复
热议问题