El *_*uli 11 android kotlin value-class android-room
我正在尝试使用具有值类的房间实体:
@JvmInline
value class UserToken(val token: String)
Run Code Online (Sandbox Code Playgroud)
和实体:
@Entity(tableName = TABLE_AUTH_TOKEN)
data class TokenEntity(
@PrimaryKey val id: Int = 0,
val token: UserToken
)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
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).
public final class TokenEntity {
^
Run Code Online (Sandbox Code Playgroud)
是否可以使用经济舱的房间?我找不到任何关于此的信息。谢谢
根据Google Issue Tracker,Room 版本现在支持值类2.6.0-alpha01。为了能够构建,请按照下列步骤操作:
对于 Room 编译器,使用 KSP 而不是 KAPT。将插件添加到根build.gradle,或者您可以参考从 KAPT 迁移到 KSP指南
添加到项目build.gradle
plugins {
...
id 'com.google.devtools.ksp' version '1.8.10-1.0.9' apply false
}
Run Code Online (Sandbox Code Playgroud)
在应用程序build.gradle中
plugins {
....
id 'com.google.devtools.ksp'
}
android {
...
ksp {
arg("room.generateKotlin", "true")
}
}
dependencies {
...
implementation "androidx.room:room-ktx:2.6.0-alpha01"
ksp "androidx.room:room-compiler:2.6.0-alpha01"
}
Run Code Online (Sandbox Code Playgroud)
可选:如果值类有公共构造函数,则无需TypeConverter再为其编写。但是,如果它具有private constructor或如果它是具有 的第三方类internal constructor,则需要提供TypeConverter来构建它。例如,kotlin.time.Duration。
class Converters {
@TypeConverter
fun formDuration(value: Duration?): Long? {
return value?.inWholeMilliseconds
}
@TypeConverter
fun toDuration(time: Long?): Duration? {
return time?.let { time.milliseconds }
}
}
@Database(
...
)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1535 次 |
| 最近记录: |