In Room 3.0, how do you store an Instant property on an entity, and where do you register the converter that makes it work?
answer
- SQLite stores only a few types
- two one-argument functions
- Instant to Long and back
- registered at a scope
- query parameters convert too
basics
~10 sRoom 3.0 stores an Instant through two @ColumnTypeConverter functions, Instant to Long epoch millis and back, registered with @ColumnTypeConverters on the @Database class so every entity and DAO can use them.
solid answer
~40 sRoom maps a fixed set of types natively: primitives, `String`, `ByteArray`, and built-in handling for enums and `UUID`. For an `Instant` I write two `@ColumnTypeConverter` functions in an `object`: one turns the `Instant` into a `Long` with `toEpochMilli()`, the other turns the `Long` back into an `Instant`. I register the holder with `@ColumnTypeConverters(InstantConverters::class)` on the `@Database` class, which makes it available to every entity and DAO; I can narrow it to a `@Dao`, an `@Entity`, one property or one DAO parameter instead. Room also uses the pair when it binds an `Instant` query parameter, so `WHERE startsAt >= :from` compares numbers, and epoch millis keep range queries and `ORDER BY` correct. On Room 2.x the same code uses `@TypeConverter` and `@TypeConverters` from `androidx.room`.
code
kotlin · 36 linesimport androidx.room3.ColumnTypeConverter
import androidx.room3.ColumnTypeConverters
import androidx.room3.Dao
import androidx.room3.Database
import androidx.room3.Entity
import androidx.room3.PrimaryKey
import androidx.room3.Query
import androidx.room3.RoomDatabase
import java.time.Instant
object InstantConverters {
@ColumnTypeConverter
fun toEpochMillis(instant: Instant?): Long? = instant?.toEpochMilli()
@ColumnTypeConverter
fun fromEpochMillis(value: Long?): Instant? = value?.let(Instant::ofEpochMilli)
}
@Entity(tableName = "events")
data class Event(
@PrimaryKey val id: Long,
val title: String,
val startsAt: Instant,
)
@Dao
interface EventDao {
@Query("SELECT * FROM events WHERE startsAt >= :from ORDER BY startsAt")
suspend fun upcoming(from: Instant): List<Event>
}
@Database(entities = [Event::class], version = 1)
@ColumnTypeConverters(InstantConverters::class)
abstract class EventDatabase : RoomDatabase() {
abstract fun eventDao(): EventDao
}go deeper
Recall the two converter functions, the annotation that registers them and that the @Database class is the usual place to put it.
Explain the scopes a converter can be registered at, that query parameters are converted too, and why epoch millis beat toString() text for ranges.
Show that a converter's encoding is part of the stored schema: changing it for an existing column needs a migration, and nullability must match the column.
Treat time encoding as a team convention: one database-wide converter for each time type, documented units and precision, and no per-entity variants without a reason.
## Why Room needs a converter at all **Room** is Android's compile-checked layer over SQLite. For every property of an `@Entity` it must know how to write the value into a SQLite column and how to read it back into the property. Out of the box it handles a fixed set of types: Kotlin primitives and their nullable forms, `String`, `ByteArray`, plus built-in handling for enums, `UUID` and `ByteBuffer`. A `java.time.Instant` is none of those, so Room's code generator stops the build and asks for a way to store it. A **column type converter** is that way: a pair of plain functions that translate the type Room does not know into one it does. In Room 3.0 each function carries `@ColumnTypeConverter`; in Room 2.x the same annotation is spelled `@TypeConverter`. ## Writing the converter pair Each converter function takes exactly **one parameter** and returns a non-`Unit` value. For a column Room both writes and reads, you need **both directions**: 1. `Instant` to `Long`, used when Room inserts, updates or binds a parameter. 2. `Long` to `Instant`, used when Room reads a row from a query result. Put the functions in a Kotlin `object` and Room calls them directly; put them in a class and Room creates an instance of it for you. (When the class needs a dependency handed to it, it becomes a *provided* converter, which is a separate, builder-level mechanism.) ## Registering it, and the scopes it can have Writing the functions is not enough: Room only uses converters that are **registered** with `@ColumnTypeConverters(InstantConverters::class)` (Room 2.x: `@TypeConverters`). Where you put that annotation decides who may use the converter: | Placed on | Who can use the converter | |---|---| | the `@Database` class | every entity and DAO in that database | | a `@Dao` | every function in that DAO | | an `@Entity` or result data class | every property of that class | | one entity property | only that property | | a DAO function | every parameter of that function | | one DAO function parameter | only that parameter | Most apps register general converters such as time types once on the `@Database` class. A narrower scope is useful when one entity needs a different encoding, or when you want a converter to stay local to the code that owns it. Registration is also what makes **query parameters** work. A DAO function `suspend fun upcoming(from: Instant): List<Event>` with `WHERE startsAt >= :from` binds the `Long` your converter returns, so the comparison runs on numbers in SQLite. ## Choosing the stored form for a time value The converter decides what the column *is*, and that choice outlives the code: | Stored form | Column | Range queries and ordering | Cost | |---|---|---|---| | epoch milliseconds (`toEpochMilli()`) | INTEGER | numeric, index-friendly | drops sub-millisecond precision | | `Instant.toString()` | TEXT | unreliable: the fractional part is omitted when it is zero, so strings vary in length | human-readable in a database inspector | | fixed-width UTC text | TEXT | correct while every value uses the same format | larger, and the format becomes a contract | For an events app that lists upcoming events, **epoch milliseconds** is the usual choice. A `LocalDate` with no time of day is often stored as ISO text such as `2026-10-10`, which is fixed width and sorts correctly. ## Nullability and common mistakes - A nullable column (`Instant?`) needs converters that can handle `null`. The Room 3.0 documentation example simply declares nullable types on both sides, which handles a nullable column explicitly. Room 2.4 added a null-aware analysis when processing with KSP that can wrap a non-null converter in a null check for you. - Forgetting to register the holder class is the most frequent mistake: the functions compile, and Room still reports that it cannot store the property. - Converters change **column values and parameters only**. They never transform a whole row or a DAO function's return type. - Changing a converter's output format for an existing column changes the meaning of stored data. Rows already on users' phones keep the old encoding, so that change needs a migration. ## Room 2.x spelling Code on Room 2.8.5 uses `androidx.room.TypeConverter` and `androidx.room.TypeConverters` with exactly the same shape. Room 3.0.0-rc01 renamed `@TypeConverter` to `@ColumnTypeConverter`, and Room 3.0 registers converters with `@ColumnTypeConverters` in `androidx.room3`. The mechanics described above are the same in both majors.
- Why not store the Instant as the text that Instant.toString() produces?It works for display, but `Instant.toString()` omits the fractional seconds when they are zero, so the strings vary in length and can sort out of order as text. Range queries and `ORDER BY` then return wrong results. Epoch milliseconds compare numerically and index well; if you need text, format every value as fixed-width UTC.
- The entity's column is a nullable Instant?, but your converters take and return non-null types. What should you expect?Since Room 2.4, when Room processes code with KSP it reads Kotlin nullability and can wrap a non-null converter in a null check for a nullable column; KAPT and Java builds lack that information. The safe, explicit form is the one Room 3.0's documentation uses: declare `Long?` to `Instant?` and `Instant?` to `Long?`.
- How would you make a converter apply to one entity property only?Put `@ColumnTypeConverters(SomeConverters::class)` on that property instead of on the `@Database` class. Room then uses it for that property alone. The same annotation on a DAO function parameter limits it to that parameter, which helps when one query needs a different encoding from the rest of the database.
- Room serializes any Kotlin object into a column automatically
- Every converter must be passed to the database builder to work
- Converters apply to entity columns but never to query parameters
- Room 3.0 still uses @TypeConverter from androidx.room
- Storing time as Instant.toString() text always sorts correctly
Assumes Room 3.0 (androidx.room3): 3.0.0-rc01 renamed @TypeConverter to @ColumnTypeConverter and 3.0 registers converters with @ColumnTypeConverters; Room 2.8.5 code uses @TypeConverter and @TypeConverters.