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
    }

}

1 Answer 1

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")
Sign up to request clarification or add additional context in comments.

3 Comments

So then there's no needs for secondary constructors with different number of arguments?
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)
Note that if you want the different constructors accessible from Java code, you'll need to add the @JvmOverloads annotation to the constructor. stackoverflow.com/questions/35748906/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.