Can Kotlin data class have more than one constructor?

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

    A Kotlin data class must have a primary constructor that defines at least one member. Other than that, you can add secondary constructors as explained in Classes and Inheritance - Secondary Constructors.

    For your class, and example secondary constructor:

    data class User(val name: String, val age: Int) {
        constructor(name: String): this(name, -1) { ... }
    }
    

    Notice that the secondary constructor must delegate to the primary constructor in its definition.

    Although many things common to secondary constructors can be solved by having default values for the parameters. In the case above, you could simplify to:

    data class User(val name: String, val age: Int = -1) 
    

    If calling these from Java, you should read the Java interop - Java calling Kotlin documentation on how to generate overloads, and maybe sometimes the NoArg Compiler Plugin for other special cases.

    0 讨论(0)
  • 2020-12-30 19:25

    Yes, but each variable should be initialized, so you may set default arguments in your data class constructor, like this:

    data class Person(val age: Int, val name: String = "Person without name")
    

    Now you can create instance of this data class in two ways

    • Person(30)
    • Person(20, "Bob")
    0 讨论(0)
  • 2020-12-30 19:30

    Yes, we can use like below code, and in primary constructor for data class should have min one parameter.

    data class SampleData(val name: String, val age: Int) {
        constructor(name: String, age: Int, email: String) : this(name, age) {
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题