Default Values and Partial Entities
We have already seen how Room supports Kotlin default values on properties:
class CustomColumnNameEntity(
@PrimaryKey
val id: String,
val title: String,
@ColumnInfo(name = "words") val text: String? = null,
val version: Int = 1
) {
Here, text
and version
both have default values. Really, these have nothing to do with Room — they are a pure Kotlin concept. However, in the end, if we create a CustomColumnNameEntity
instance without supplying text
or version
, we get those defaults.
But, in Room 2.2.0, we got another option for default values… one that on the surface seems pointless, as it does not work with @Insert
operations. Principally, this appears to be tied to another feature added in that same release: partial entity support.
In this chapter, we will explore both of these features.
Default Values, and the Other Default Values
The new option for default values comes in the form of a defaultValue
property on the @ColumnInfo
annotation:
@Entity(tableName = "defaultValue")
class DefaultValueEntity(
@PrimaryKey
val id: String,
val title: String,
@ColumnInfo(defaultValue = "something")
val text: String? = null,
@ColumnInfo(defaultValue = "123")
val version: Int = 1
) {
Here, as in the example shown earlier, we have text
and version
properties on an entity (DefaultValueEntity
), and in Kotlin, we have those properties default to null
and 1
, respectively. However, we also have @ColumnInfo
annotations on those, where each has a defaultValue
property. The one on text
says the default value is something
, while the one on version
says that the default value is 123
. So, for each property, we have two separate default values declared: one via Kotlin and one via the defaultValue
annotation property… and both are different.
The Kotlin default values are for Kotlin’s use. You can create instances of DefaultValueEntity
without supplying values for text
and/or version
.
The @ColumnInfo
defaultValue
properties are for SQLite’s use. If you attempt to INSERT
a value into the table without providing values for the text
and/or version
columns, the defaultValue
properties take effect. Basically, the defaultValue
properties are embedded directly in the CREATE TABLE
SQL statement generated from our @Entity
declaration:
CREATE TABLE IF NOT EXISTS `defaultValue` (`id` TEXT NOT NULL, `title` TEXT NOT NULL,
`text` TEXT DEFAULT 'something', `version` INTEGER NOT NULL DEFAULT 123,
PRIMARY KEY(`id`))
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.