Reputation: 154
I've trying to add type converter to my entity, but I found the it only work at database, dao and entity scope, not in entity field scope.
For example : when I add type converter in Entity scope like this, it works fine.
@Entity(tableName = "chat_history")
@TypeConverters(ChatEntityConverter::class)
class ChatHistoryEntity (
@PrimaryKey
@NonNull
@ColumnInfo(name = "history_id") val HID: Long?,
@ColumnInfo(name = "history_name") var pairedName: String?,
@ColumnInfo(name = "history_last_message") var lastMessage: String?,
@ColumnInfo(name = "history_last_date")
var lastDate: Date?
)
But if I move it into Entity field scope, it fail to compile.
@Entity(tableName = "chat_history")
class ChatHistoryEntity (
@PrimaryKey
@NonNull
@ColumnInfo(name = "history_id") val HID: Long?,
@ColumnInfo(name = "history_name") var pairedName: String?,
@ColumnInfo(name = "history_last_message") var lastMessage: String?,
@TypeConverters(ChatEntityConverter::class)
@ColumnInfo(name = "history_last_date")
var lastDate: Date?
)
It shows the error message like this :
error: Cannot figure out how to save this field into database.
My converter is :
class ChatEntityConverter {
@TypeConverter
fun fromTimeStamp(date: Long?): Date? {
return when(date) {
null -> null
else -> Date(date)
}
}
@TypeConverter
fun dateToTimeStamp(date: Date?): Long? {
return when(date) {
null -> null
else -> date.time
}
}
}
Since it also convert long type to date type, I don't want it to work on Entity scope. Only in date type field scope. But I just couldn't put it there and compile it.
Upvotes: 2
Views: 862
Reputation: 1006869
@TypeConverters
works on a field. You are using Kotlin, so you are working more directly with properties. To apply the annotation to the backing field, use @field:TypeConverters
instead of @TypeConverters
.
Upvotes: 6