How do you define a Room table for a Kotlin data class?

Tests your grasp of the minimum Room entity contract. A strong answer cites Entity and PrimaryKey, notes Kotlin defaults work out of the box, and mentions ColumnInfo for renaming.
WHAT THIS TESTS: This question checks whether you understand the minimum annotation contract Room requires to map a Kotlin data class to a SQLite table. At the senior level, interviewers expect you to know that Room is annotation-driven, that Kotlin data classes are first-class citizens, and that only a small subset of properties actually need explicit annotations. The question also reveals whether you confuse the entity layer with DAO or Database abstractions.
A GOOD ANSWER COVERS: Four things in order. First, the class itself must be annotated with Entity, which tells Room to create a corresponding table; you can optionally supply a table name if you want it to differ from the class name. Second, at least one property must be annotated with PrimaryKey, because Room enforces a primary key on every table; you can set autoGenerate to true if it is an integer type. Third, Room automatically maps Kotlin properties to columns using the property names and types, so no additional annotations are required for basic fields. Fourth, ColumnInfo is optional and only used when you need the database column name to differ from the Kotlin property name.
COMMON WRONG ANSWERS: Three red flags stand out. One, claiming that every property needs an explicit ColumnInfo or other annotation; Room defaults are designed to reduce boilerplate. Two, omitting PrimaryKey entirely or suggesting a table can exist without one; Room will throw a compile-time error if it is missing. Three, confusing the Entity annotation with Database or Dao, such as describing query methods or repository logic instead of schema definition.
LIKELY FOLLOW-UPS: Expect the interviewer to ask how you handle embedded objects with Embedded, how you define indices or foreign keys inside the Entity annotation, or how Room handles Kotlin non-null types versus nullable Java types. They may also probe migrations, asking what happens when you add a new property to this User class and ship an update.
ONE CONCRETE EXAMPLE: A minimal User entity looks like this in concept. A Kotlin data class named User is annotated with Entity. Inside, an integer property id is marked with PrimaryKey and autoGenerate set to true. String properties like name and email require no extra annotations because Room infers them automatically. If you wanted the email column stored as user_email, you would place ColumnInfo with name set to user_email on that property. That is the entire essential surface area.
Source: developer.android.com
Read the original → developer.android.com
- #android
- #room
- #kotlin
- #database
- #entities
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.