12
votes

I've integrated Room in my project. In this project some classes are in Kotlin and some are in Java. After I converted my Java file to Kotlin using Android Studio Ctrl+Alt+Shift+K combination, I've started facing this error:

TypeConverter() has private access in TypeConverter

in the generated java class, at this line:

private final PointOfInterest.TypeConverter __typeConverter_5 = new PointOfInterest.TypeConverter();

But TypeConverter in PointOfInterest class is public.

2
Can you add your PointOfInterest class with TypeConverter? - MichaƂ Baran

2 Answers

30
votes

Don't change the object keyword to class (as the accepted answer suggests). The object declaration guarantees the Singleton pattern.

After automatics conversion of TypeConverter java file to kotlin file, you should mark all inner converter functions with @JvmStatic so Room can use them as regular static functions.

Take a look at the official Android Architecture Components samples, specifically the GithubTypeConverters.kt. Also, this discussion can be useful. And this is my DateTypeConverter.kt:

object DateTypeConverter {

    @TypeConverter
    @JvmStatic
    fun toDate(timestamp: Long?) = timestamp?.let { Date(timestamp) }

    @TypeConverter
    @JvmStatic
    fun toTimestamp(date: Date?) = date?.time

}
24
votes

I my particular case, I converted my Java file to Kotlin using android studio ctrl+alt+shift+k key combination. What android studio did is that, it converted my class TypeConverter classes to type of object TypeConverter and I just couldn't figured out why my code stopped working. So, I manually changed object TypeConverter to class TypeConverter.

One more point regarding conversion to Kotlin: In case of Parcelable class, kotlin converted file in android studio doesn't add @JvmField on CREATOR field. So, you'll have to add it @JvmField val CREATOR manually to ensure proper working of Parcelable classes.