Note this is intentionally a Q and A to show/explain the difference, when using Room, between an Objects's default instantiaion (constrcution) values and SQLite's DEFAULT clause and how to utilise either
In Room you can code @ColumInfo(defaultValue = "a_default_value") for example (and subsequent demonstration)
@Entity
data class User(
@PrimaryKey
val userId: Long?, /* allow null for auto assigned ID */
@ColumnInfo(defaultValue = "1000")
val flag1: Int = 0,
@ColumnInfo(defaultValue = "10000")
val flag2: Int = 10,
@ColumnInfo(defaultValue = "default from column DEFAULT clause")
val otherData: String? = "default from object's default value"
)
Considering the Dao :-
@Insert
abstract fun insert(user: User): Long
Then using :-
dao.insert(User(null))
results in the Object's default values being assigned as per
User is 1 Flag1 is 0 Flag2 is 10 OtherData is default from object's default value
i.e.
- Flag1 is 0 because of
val flag1: Int = 0 - Flag2 is 10, likewise
- otherData is default from object's default value, likewise
- Flag1 is 0 because of
If using :-
dao.insert(User(100, otherData = "Blah"))
Then the result is similar except that Blah is assigned to otherData :-
User is 100 Flag1 is 0 Flag2 is 10 OtherData is Blah
So what about using defaultValue value(s)? How? (albeit it not that much use/difference)
- The above Entity has been purposefully written to include the probably unnecessary/useless difference.