Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Room auto-generate and initialization

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?

like image 350
Touloudou Avatar asked Apr 28 '19 12:04

Touloudou


People also ask

What is RoomDatabase?

RoomDatabase provides direct access to the underlying database implementation but you should prefer using Dao classes. See also: Database.

Is room an ORM?

Is Android Room an ORM? Room isn't an ORM; instead, it is a whole library that allows us to create and manipulate SQLite databases more easily. By using annotations, we can define our databases, tables, and operations.


1 Answers

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)
}
like image 129
Chetan Gupta Avatar answered Sep 28 '22 09:09

Chetan Gupta