0

I used Android studio's Kotlin plugin to convert my Java class to Kotlin. The thing is it's not Kotlin style still. I want to have Kotlin Data Class instead. But whenever I create it with a primary and secondary constructors it won't work. What would be the correct DATA Class implementation in my case?

class Task {

    @SerializedName("_id")
    var id: String? = null
    @SerializedName("text")
    var taskTitle: String? = null
    @SerializedName("completed")
    var isCompleted: Boolean? = null

    constructor(taskTitle: String) {
        this.taskTitle = taskTitle
    }

    constructor(taskTitle: String, completed: Boolean?) {
        this.taskTitle = taskTitle
        this.isCompleted = completed
    }

    constructor(id: String, taskTitle: String, isCompleted: Boolean?) {
        this.id = id
        this.taskTitle = taskTitle
        this.isCompleted = isCompleted
    }

}
nhaarman
  • 98,571
  • 55
  • 246
  • 278
MikeB
  • 257
  • 1
  • 4
  • 15

1 Answers1

6

Kotlin introduces default values for parameters in constructor. You can use them to create data class with only one constructor using Kotlin. It would look like this

data class Task(    
    @SerializedName("_id") var id: String? = null,
    @SerializedName("text") var taskTitle: String? = null,
    @SerializedName("completed") var isCompleted: Boolean? = null
)

So you can use your data class with any number of arguments for example:

var task = Task(taskTitle = "title")
var task = Task("id", "title", false)
var task = Task(id = "id", isCompleted = true)

You can even replace argument order

var task = Task(taskTitle = "title", isCompleted = false, id = "id")
Tuby
  • 3,158
  • 2
  • 17
  • 36
  • 1
    So then there's no needs for secondary constructors with different number of arguments? – MikeB Jun 09 '17 at 19:06
  • 1
    No, you must pass required parameters(none of them in this case) and the rest is optional and will be initialized to default values. If you want to have custom value for only one two parameters you can specify them by name(as described in my answer) – Tuby Jun 09 '17 at 19:08
  • 3
    Note that if you want the different constructors accessible from Java code, you'll need to add the `@JvmOverloads` annotation to the constructor. https://stackoverflow.com/questions/35748906/jvmoverloads-annotation-for-class-primary-constructor – Ruckus T-Boom Jun 09 '17 at 19:11