Room type converters

Common type converters for the Room library.

/**
 * Data type converters needed by Room to store any non primitive or String fields
 * Must include both conversations ex
 * UUID -> String
 * String -> UUID
 */
class RoomTypeConverters {

    @TypeConverter
    fun uuidFromString(id: String?): UUID? {
        return id.let { UUID.fromString(id) }
    }

    @TypeConverter
    fun stringFromUuid(uuid: UUID?): String? {
        return uuid.let { uuid.toString() }
    }

    @TypeConverter
    fun fromLocation(location: Location?): String? {
        return if (location == null) {
            null
        } else String.format(
            Locale.US, "%f,%f", location.latitude,
            location.longitude
        )

    }

    @TypeConverter
    fun toLocation(latlon: String?): Location? {
        if (latlon == null) {
            return null
        }

        val pieces = latlon.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        val result = Location("")

        result.latitude = pieces[0].toDouble()
        result.longitude = pieces[1].toDouble()

        return result
    }

    @TypeConverter
    fun fromStringToStringList(list: String): List<String> {
        return Gson().fromJson(list, object : TypeToken<List<String>>() {}.type)
    }

    @TypeConverter
    fun fromStringListToString(list: List<String>): String {
        return Gson().toJson(list)
    }

    @TypeConverter
    fun fromStringToMyEnum(str: String): MyEnum {
        return when (str) {
            "PENDING" -> MyEnum.PENDING
            "NONE" -> MyEnum.NONE
            else -> MyEnum.ACCEPTED
        }
    }

    @TypeConverter
    fun fromMyEnumToString(enum: MyEnum): String {
        return enum.toString()
    }
}

Usage

Gradle dependency:

implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"

Sample usage:

@TypeConverters(RoomTypeConverters::class)
abstract class MyDatabase : RoomDatabase() {

    abstract fun myDao(): MyDao

    companion object {
        @Volatile
        private var instance: MyDatabase? = null

        fun getInstance(context: Context): MyDatabase? {
            if (instance == null) {
                synchronized(MyDatabase::class) {
                    instance = Room.databaseBuilder(
                        context.applicationContext,
                        MyDatabase::class.java, "my_database"
                    )
                        .fallbackToDestructiveMigration()
                        .build()
                }
            }
            return instance
        }
    }
}