Search code examples
androidkotlinandroid-roomdata-class

Can I use same data class for Room and API calls in Kotlin?


I have a fairly simple data class in my app:


data class ModelSlide(
    val title: String,
    val info: String,
    val image: String
)


When I create an API call, I get back json. I use the information from the json and the ModelSlide to create ArrayList<ModelSlide>. Then I load this arrayList in a viewpager by using an adapter. Fairly simple stuff.

Now, I've just started working with Room. Sadly, due to being quite new at this, I've been creating duplicate data classes for Room like so:



@Entity
data class User(
    @PrimaryKey val slideId: Int,
    @ColumnInfo(name = "title") val title: String?,
    @ColumnInfo(name = "info") val firstName: String?,
    @ColumnInfo(name = "image") val lastName: String?
)

This approach works, but to me, a beginner at Room, this somehow seems redundant.

Can I combine both my workflows, with the same data class?

To Recap

  • I use the first ModelSlide class to create ArrayList<ModelSlide> and load the slides into a Viewpager with the help of an adapter

  • I created the second data class for ModelSlide to use with Room library

My question

Can I use the same data class for creating ArrayLists and with Room?

If so, how would the data class look like?


Solution

  • According your requirements you can use single data class for creating ArrayLists and with Room. Check below:

    @Entity(tableName = "User")
    data class ModelSlide(
        val title: String?,
        val info: String?,
        val image: String?,
        @PrimaryKey(autoGenerate = true)
        val slideId: Int = 0
    )