8

I have a Room database that contains Stuff entities. These entities have an ID that will be auto-generated:

@Entity(tableName = "stuff")
data class Stuff(val text: String) {
    @PrimaryKey(autoGenerate = true) var id: Int = 0
}

There are two things I don't like with my code:

  1. I am initializing the id with 0, even though it should be initialized by Room.
  2. The id data member is mutable.

I tried using lateinit var but the compiler wouldn't let me do it on a primitive type. Is there a way to overcome the two issues mentioned above in Kotlin?

Touloudou
  • 2,079
  • 1
  • 17
  • 28

1 Answers1

2

what do think about solving this using a secondary constructor?

@Entity(tableName = "stuff")
data class Stuff(
  @PrimaryKey(autoGenerate = true)
  val id: Int,
  val text: String
) {
   constructor(text: String) : this(0,text)
}
Chetan Gupta
  • 1,477
  • 1
  • 13
  • 22