Can Kotlin data class have more than one constructor?

前端 未结 9 1198
没有蜡笔的小新
没有蜡笔的小新 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:12

    Updated answer for data classes:

    Yes you can, but you will need to delegate everything to the primary constructor

    data class User(val name: String, val age: Int)
    {
        constructor(name: String): this(name, -1) {
        }
    
        constructor(age: Int): this("Anon", age) {
        }
    }
    
    // Anon name: Anon
    println("Anon name: " + User(30).name)
    
    // No age: -1
    println("No age: " + User("Name").age)
    
    // Name: Name age: 20
    val u = User("Name", 20)
    println("Name: " + u.name + " age: " + u.age)
    

    You can also set default values in your primary constructor as Alexey did.

提交回复
热议问题