Android Room 具有 kotlin 价值等级?

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)

是否可以使用经济舱的房间?我找不到任何关于此的信息。谢谢

Wil*_*ran 6

根据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)


Oma*_*wky -2

我认为是的,如果你可以为它提供一个类型转换器,在需要存储时将其更改为某种原始数据类型( int 、 string 、 long ...等),并在需要存储时将其更改回其类类型它是从数据库中获取的。

您可以从这里阅读有关类型转换器的信息

使用 Room 引用复杂数据

除此之外,您的另一个类应该是一个实体,并使用Relation将两个实体绑定在一起。

至少这是我所知道的如何使用 Room。