Can Kotlin data class have more than one constructor?

前端 未结 9 1371
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 18:48

I know that data class are like simple models in kotlin with getters and setter by default and are as simple this:

data class User(val name: String, val age:         


        
9条回答
  •  不知归路
    2020-12-30 19:14

    Data class will ensure consistency and meaningful behavior also we need to have val for immutability.

    data class SampleData(val name: String, val age: Int, val email: String ?= null) {
    constructor(name: String, age: Int) : this(name, age, null) {
    
    }
    

    }

    secondary constructor must delegate to the primary constructor in its definition, so to maintain the immutability, having "null" will work.

提交回复
热议问题