According to the Google Issue Tracker, value classes are now supported on Room version 2.6.0-alpha01
. To be able to build, please follow these steps:
Use KSP instead of KAPT for the Room compiler. Add the plugin to the root build.gradle, or you can refer to the Migrate from KAPT to KSP guide
Add to the project build.gradle
plugins {
...
id 'com.google.devtools.ksp' version '1.8.10-1.0.9' apply false
}
In the app 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"
}
Optional: If the value class has a public constructor, you do not need to write a TypeConverter
for it anymore. However, if it has a private constructor
or if it is a third-party class with an internal constructor
, you need to provide a TypeConverter
to build it. For example, 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() {
...
}