Skip to content

Type Converters

Devrath edited this page Jun 11, 2021 · 1 revision

What are type converters

  • Type converters are used to store complex data in the database.
  • Retrieving the complex data from the database.
  • Type converts acts as a layer between the database and the tables.
  • Here we specify a mechanism to convert to and convert from` database.
  • We define a custom Type converter class.
class DateConverter {

  @TypeConverter
  fun fromTimestamp(value: Long?): Date? {
    return Date(value ?: 0)
  }

  @TypeConverter
  fun dateToTimestamp(date: Date?): Long = date?.time ?: 0
}
  • For the property name, we annotate with a @TypeConverters annotation that holds the converter class defined.
@Parcelize
@Entity
data class Review(
    @PrimaryKey
    val id: String = UUID.randomUUID().toString(),
    val bookId: String,
    val rating: Int,
    val notes: String,
    val imageUrl: String,
    @TypeConverters(DateConverter::class)
    val lastUpdatedDate: Date,
    @TypeConverters(ReadingEntryConverter::class)
    val entries: List<ReadingEntry>
) : Parcelable