Search code examples
kotlinmethodsgetsetdata-class

How to establish getter & setter for secondary constructor in data class for kotlin?


I need a data class with two different constructors as shown. But how do I do getter & setter for the secondary constructor of data class in Kotlin? I tried multiple changes, not able to figure it out. In the below snippet, I am not getting the right import for get() and set()

data class user(var phone: String) {
    constructor(phone: String, name : String) : this(phone) {
        var name: String = name
        get()= field
        set(value) {
            field = value
        }
      }
    }


Solution

  • It appears you want two constructors, one which only requires a "phone" argument and another which requires both a "phone" and "name" argument. Overall, your data class will have two properties regardless of which constructor is used: phone and name. You could accomplish this with the following:

    data class User(var phone: String) {
    
        var name: String = ""
    
        constructor(phone: String, name: String) : this(phone) {
            this.name = name
        }
    }
    

    However, as this is Kotlin, you should prefer default parameter values over overloaded functions/secondary constructors:

    data class User(var phone: String, var name: String = "")