Search code examples
androidkotlinconstructorentity

How to accomodate different arguments for entity class


I am calling my entity class in an if/else-if statement for 2 different conditions and the values I pass into the parameters depend on the condition. In the if block, I am passing 3 parameters and in the else-if block, I am passing 4. The entity's object is throwing an error because it is expecting 4 parameters. I want the first parameter to be optional and I'd like to know if there is a way to do that in Kotlin.

This is my entity class:

@Entity(tableName = "entry_table")
data class Entry(
    @PrimaryKey(autoGenerate = true) 
    var id: Int? = null, 

    val username: String? = null, 
    val hint: String? = null, 
    val password: String? = null)

And this is the if/else-if block where I'm inserting values into the entity object:

if (requestCode == ADD_ENTRY_REQUEST && resultCode == Activity.RESULT_OK) {
            ...

            val entry = Entry(username, hint, password)
            ...

        } else if (requestCode == EDIT_ENTRY_REQUEST && resultCode == Activity.RESULT_OK) {
            ...

            val entry = Entry(id, username, hint, password)
            ...

        }

In Java, you could solve this problem by creating 2 constructors with matching number of parameters but I wonder if we can do the same in Kotlin or if there is a different approach.


Solution

  • You can try moving the id to the end, like so:

    @Entity(tableName = "entry_table")
    data class Entry(
        val username: String? = null, 
        val hint: String? = null, 
        val password: String? = null,
        @PrimaryKey(autoGenerate = true) 
        var id: Int? = null)
    

    And then creating it like:

    val entry = Entry(username, hint, password, id)
    

    Or, if you want to keep the id as the first parameter, you can use named arguments like this:

    val entry = Entry(username = username, hint = hint, password = password)
    

    Hope that helps!