6

Is there a way to have one Room TypeConverter that will take multiple table fields and combine them into some object?

As an example, let's assume I have a table Foo that has columns INT numerator, INT denominator (together representing a fraction), and INT unit (unit maps to an enum of measurement units). I want to combine them into MyScalar(Fraction(numerator, denominator), unit). For example, possibly take a row (1, 5, 2) (where the 2 maps to MeasurementUnit.KG) and use a @TypeConverter to turn this row into MyScalar(Fraction(1,5), MeasurementUnit.KG).

Right now I'm just doing

data class MyEntity(
    val numerator: Int, 

    val denominator: Int, 

    @TypeConverters(IntAndUnitConverter::class) 
    val unit: MeasurementUnit
) {
    fun combine(): MyScalar {
        return MyScalar(Fraction(numerator, denominator), unit)
    }
}

with

data class MyScalar(val value: Fraction, val unit: MeasurementUnit)

Seems to do the trick, but I find the idea appealing of just having my @Entity have @TypeConverters(SomeThreeColumnConverter::class) up top and not worry about remembering to invoke combine() or anything like that.

I don't think it's possible, but wanted to check.

bhavya_karia
  • 760
  • 1
  • 6
  • 12
user1713450
  • 1,307
  • 7
  • 18

0 Answers0