I'm learning Android Jetpack, the following code is from a sample project at https://github.com/android/sunflower.
The GardenPlanting.kt code is to design a table, I'm very strange why the author define the table fields in two position, you see that @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") is located the inner of the class.
I think that Code B is easy to understand, right?
GardenPlanting.kt
@Entity(
tableName = "garden_plantings",
foreignKeys = [
ForeignKey(entity = Plant::class, parentColumns = ["id"], childColumns = ["plant_id"])
],
indices = [Index("plant_id")]
)
data class GardenPlanting(
@ColumnInfo(name = "plant_id") val plantId: String,
@ColumnInfo(name = "plant_date") val plantDate: Calendar = Calendar.getInstance(),
@ColumnInfo(name = "last_watering_date")
val lastWateringDate: Calendar = Calendar.getInstance()
) {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
var gardenPlantingId: Long = 0
}
Code B
data class GardenPlanting(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") val id: String,
@ColumnInfo(name = "plant_id") val plantId: String,
@ColumnInfo(name = "plant_date") val plantDate: Calendar = Calendar.getInstance(),
@ColumnInfo(name = "last_watering_date")
val lastWateringDate: Calendar = Calendar.getInstance()
) {
var gardenPlantingId: Long = 0
}