Migrate model from Java class to Kotlin data class
Fix build error "Entities and Pojos must have a usable public constructor" by updating Room from 1.0.0 to 1.1.1
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).
florina-muntenescu commented on 14 Oct 2017 Thanks @rs146 for reporting this. The problem here is that Room can't find the right constructor for the elements in the relation, when the element is Int (or Integer in Java). I created an issue on our internal tracker for this but chances are this won't be fixed for the 1.0 release, unfortunately. https://github.com/googlesamples/android-architecture/issues/434
Fix error "IllegalArgumentException: Parameter specified as non-null is null:
The exception is pretty clear: you're passing null for the parameter. By default all variables and parameters in Kotlin are non-null. If you want to pass null parameter to the method you should add ? to it's type. https://stackoverflow.com/questions/44885783/illegalargumentexception-parameter-specified-as-non-null-is-null
- constructor(id: Int, title: String, description: String, imageHref: String) {
+ constructor(id: Int, title: String?, description: String?, imageHref: String?) {
@Ignore
- constructor(title: String, description: String, imageHref: String) {
+ constructor(title: String?, description: String?, imageHref: String?) {
总结:如果数据可能为null,一定要后缀?
自动转成的Kotlin代码仍然是Java style,需要修改为 Kotlin data class 定义 properties 的方式
@Entity(tableName = "ArticleTable", indices = [Index(value = *arrayOf("title"), unique = true)])
data class Article (
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
@SerializedName("title")
val title: String?,
@SerializedName("description")
val description: String?,
@SerializedName("imageHref")
val imageHref: String?
)
Kotlin 可以通过下述方式初始化 data class
return Article(title = title, description = description, imageHref = imageHref)
2018-08-27 Weiyi Li