Reputation: 257
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
}
}
Upvotes: 0
Views: 841
Reputation: 3253
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")
Upvotes: 6