Home > Back-end >  kotlin data class constructors not getting picked up
kotlin data class constructors not getting picked up

Time:11-07

I am creating a data class in kotlin as such


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

}

In my main function, I can access the objects as such:

fun main(){

    val x = User("foo", 5, "M")
    println(x.name)
    println(x.age)
    println(x.size) // does not work
}

My problem is that I can't get access to size.

What I am trying to do is, create a data class where top level params are the common items that will be accessed, and in the constructors, have additional params that fit certain situations. The purpose is so that I can do something like

// something along the lines of 
if (!haveSize()){
    val person = User("foo", 5, "M")
} else {
     val person = User("foo", 5)
    }
}

Any ideas?

CodePudding user response:

In Kotlin you do not need separate constructors for defining optional constructor params. You can define them all in a single constructor with default values or make them nullable, like this:


data class User(val name: String, val age: Int, val size: String = "M")
fun main(){
    val x = User("foo", 5, "L")
    val y = User("foo", 5)

    println(x.size) // "L" from call site
    println(y.size) // "M" from default param
}

CodePudding user response:

You can not access size variable, because this is from secondary construct, but we have alternative variant.

data class User(var name: String, var age: Int) {

 var size: String

 init {
     size = "size"
  }

constructor(name: String, age: Int, size: String) : this(name, age) {
    this.size = size
  }
}
  • Related