Room Type Converters: Teach Your Database New Tricks

Room Type Converters are translators for your database, teaching it to store types it doesn't natively understand, like `Date`. They let you persist simple objects by converting them to primitives like `Long`. The footgun is faking object relations with them.
WHY IT EXISTS Room is an abstraction over SQLite, which only stores a few basic data types (like TEXT, INTEGER, REAL). Room needs a way to handle common but non-primitive Java/Kotlin types like Date or UUID without forcing the developer to manually convert them before every database operation.
THE MENTAL MODEL Think of a Type Converter as a customs agent for your database. Your app has a "foreign" object (like a Date) that it wants to store. The database only accepts "local currency" (primitives like Long). The Type Converter handles the exchange, converting the Date to a Long on the way in, and back to a Date on the way out, making the process seamless for your app code.
HOW IT WORKS You create a class with methods annotated with @TypeConverter. One method takes your custom type and returns a primitive Room understands (e.g., fun fromDate(date: Date): Long). A second method does the reverse (e.g., fun toDate(timestamp: Long): Date). Finally, you register this converter class with your RoomDatabase using the @TypeConverters annotation. Room then automatically finds and applies these conversions whenever it encounters your custom type in an Entity or DAO.
WHEN TO USE IT Use converters for simple, self-contained data types that don't have their own relationships. Good examples include: converting a Date to a Long timestamp, a UUID to a String, an Enum to its String name, or a simple List<String> to a single JSON-formatted or delimited string.
WHEN NOT TO USE IT Avoid using converters to simulate object relationships. For instance, if a User has a List<Post>, do not serialize the list of Post objects into a JSON string and store it in the User table. This is a major footgun because it prevents you from querying posts directly, breaks database normalization, and makes updates inefficient. For object relationships, use Room's @Embedded and @Relation annotations.
ONE CANONICAL EXAMPLE The most common use case is handling dates. A converter for java.util.Date would have two functions. The first, fun fromDate(date: Date?): Long?, would return date?.time. The second, fun toDate(value: Long?): Date?, would return value?.let { Date(it) }. This allows you to declare a Date field in your @Entity and have Room store it as a simple, indexable LONG in the underlying SQLite table.
Read the original → developer.android.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.