Ove*_*vel 21 android constructor kotlin android-components android-room
我尝试在我的android kotlin项目中实现持久库,但在编译时捕获此错误:
错误:由于多个构造函数适合,Room无法选择构造函数.尝试使用@Ignore注释不需要的构造函数.
错误代码:
@Entity
data class Site(
var name: String = "",
var url: String = "",
@PrimaryKey(autoGenerate = true) var id: Long = 0)
Run Code Online (Sandbox Code Playgroud)
Ove*_*vel 14
我有这个错误,因为Kotlin显然为一个具有默认参数值的Kotlin构造函数生成了多个Java构造函数.工作代码见下:
@Entity
data class Site(
var name: String,
var url: String,
@PrimaryKey(autoGenerate = true) var id: Long)
Run Code Online (Sandbox Code Playgroud)
上述解决方案都不是好的,因为它们可以工作但可能会导致错误.
Kotlin的Data Class使用默认构造函数生成多个方法.这意味着使用您分配给构造函数的属性生成equals(),hashCode(), toString(),componentN()函数和copy().
使用上面的解决方案
@Entity data class Site(@PrimaryKey(autoGenerate = true) var id: Long) {
@Ignore constructor() : this(0)
var name: String = ""
var url: String = ""
}
Run Code Online (Sandbox Code Playgroud)
仅为id生成以上列出的所有方法.使用equals会导致不必要的质量,与toString()相同.解决这个问题需要您在构造函数中包含要处理的所有属性,并使用ignore like添加第二个构造函数
@Entity data class Site(
@NonNull @PrimaryKey(autoGenerate = true) var id: Long,
var name: String = "",
var url: String = "") {
@Ignore constructor(id = 0, name = ", url = "") : this()
}
Run Code Online (Sandbox Code Playgroud)
你应该记住,你通常使用数据类来拥有像toString和copy这样的方法.只有这个解决方案能够在运行时避免不必要的错误.
| 归档时间: |
|
| 查看次数: |
11687 次 |
| 最近记录: |