Search code examples
androidkotlinandroid-room

cannot compile Room DB TypeConverter for kotlin.time.Duration


only when creating a androidx.room.TypeConverter for a kotlin.time.Duration, I get the following compiler error:

MillisKotlinDurationConverter.java:6: error: Class is referenced as a converter but it does not have any converter methods.
public final class MillisKotlinDurationConverter {
             ^

the code for MillisKotlinDurationConverter.kt is shown below, and is no different for any of the other @TypeConverters in the project:

import androidx.room.TypeConverter
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds

class MillisKotlinDurationConverter {

    @TypeConverter
    fun convert(value: Duration?): Long? = value?.inWholeMilliseconds

    @TypeConverter
    fun convert(value: Long?): Duration? = value?.milliseconds
}

I also didn't forget to add it into the @TypeConverters array for the DB

@Database(
    entities = [
        ...
    ],
    version = DATABASE_VERSION
)
@TypeConverters(
    ...,
    MillisKotlinDurationConverter::class,
    ...
)
abstract class AppDatabase : RoomDatabase() {
    ...
}

Solution

  • reposting correct answer from comments

    Solution is to store into the database something other than the Kotlin Duration, and convert it to Kotlin Duration when needed.

    kotlin.time.Duration is a value class. At runtime, it's actually a Long. today, Room compiler/interpreter is not yet capable of handling Kotlin value classes.