I'm new to Kotlin and I wish to convert my java model classes with data classes, is it possible? I mean does Ormlite support this?
I'm using OrmLite with Kotlin's data classes with no problem. The key is to specify default values for all fields, then Kotlin generates an empty constructor for the data class:
@DatabaseTable(tableName = "sample_table")
data class SampleRecord(
@DatabaseField(id = true)
var id: String? = null,
@DatabaseField(canBeNull = false)
var numField: Int? = null,
@DatabaseField
var strField: String = "",
@DatabaseField
var timestamp: Date = Date()
)
» Working example on GitHub
I converted my daos to normal classes without problems
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.table.DatabaseTable
@DatabaseTable(tableName = HabitDao.TABLE)
class HabitDao() {
companion object {
const val TABLE = "habitdao"
const val ORDER = "order"
const val ID = "id"
}
@DatabaseField(columnName = ID, generatedId = true)
var id: Int = 0
@DatabaseField(index = true)
lateinit var title: String
@DatabaseField
lateinit var intention: String
@DatabaseField(columnName = ORDER)
var order: Int = 0
constructor(title: String, intention: String) : this() {
this.title = title
this.intention = intention
}
override fun toString(): String {
return title
}
}
You just need to provide empty constructor (see the one in the class definition). Also lateinit makes properties easier to use later on.
Edit: Data classes seem to add features that are useful when you need to serialize those objects. Ormlite is able to handle normal a.k.a. Java classes already so there is no need to do that. Moreover data class is expected to contain all its fields in the constructor and you don't want the id field to be present there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With