We are trying to ignore a field in constructor of data class
@Entity(tableName = "SampleEntityTable")
data class SampleEntity(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
@Ignore
var sampleJavaClass: SampleJavaClass,
var epoch: Long = 0
)
SampleJavaClass is a class written in Java, the build fails with error:
Entities and POJOs must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
Tried the following constructors but they failed to match:
<init> -> [param:id -> matched field:id, param:sampleJavaClass -> matched field:unmatched, param:epoch -> matched field:epoch]
As you are Ignore
ing the sampleJavaClass field, Room needs a constructor that takes just the id and epoch fields (i.e. those extracted from the database columns actually stored (not ignored)) as the sampleJavaClass field is not available when building SampleEntity objects when extracting data from the database.
For example if SampleJavaClass were:-
data class SampleJavaClass(
var sjcid: Long,
var sjctext: String
)
Then you could modify the SampleEntity data class to be:-
@Entity(tableName = "SampleEntityTable")
data class SampleEntity(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
@Ignore
var sampleJavaClass: SampleJavaClass,
var epoch: Long = 0
) {
constructor(id: Int = 0, epoch: Long =0) : this(id = id, sampleJavaClass = SampleJavaClass(0,""), epoch = epoch)
}
Now if the constructor is commented out then compiling results in:-
Uncomment and:-
of course you have to consider the requirements for constructing the SampleJavaClass object when extracting from the database, which may alter exactly what constructor to utilise.