How to restrict Int values bound to database column?

Viewed 69

data class:

// Entity of query
@Entity(tableName = TABLE_NAME)
data class HistoryItem(
    @PrimaryKey(autoGenerate = true)
    val id: Int,

    @ColumnInfo(name = SEARCHED_DOMAIN)
    val searchedDomain: String,

    @ColumnInfo(name = STATUS)
    val status: Int,
)

And object of statuses:

object Statuses { 
    const val FAILURE = 0
    const val NOT_FOUND = 1
    const val FOUND = 2
}

How to make val status: Int to always be FAILURE or NOT_FOUND or FOUND? I think it should looks like this:

@Status
@ColumnInfo(name = STATUS)
val status: Int

But how to do it?

1 Answers

I would recommend using an enum class for this:

enum class Status { 
    FAILURE, NOT_FOUND, FOUND;
}

@Entity(tableName = TABLE_NAME)
data class HistoryItem(
    @PrimaryKey(autoGenerate = true)
    val id: Int,

    @ColumnInfo(name = SEARCHED_DOMAIN)
    val searchedDomain: String,

    @ColumnInfo(name = STATUS)
    val status: Status
)

However, older versions of Android Room (prior to 2.3.0) do not automatically convert enum classes, so if you're using these you will need to use a type convertor:

class Converters {

    @TypeConverter
    fun toStatus(value: Int) = enumValues<Status>()[value]

    @TypeConverter
    fun fromStatus(value: Status) = value.ordinal
}

Which requires you to add the following to your database definition:

@TypeConverters(Converters::class)

See also this answer.

Related