TypeConverters are used to convert a Type that is not handled by Room into a Type that is handled (can be stored as a single column) by Room, which are limited to basically integer types, decimal types, String types or ByteArray types.
So to convert a Coord Type it must be a single Type input and a single Type returned.
When converting to be stored (fromCoord) you need to convert the 2 values lat and lon to a single value of a Type that can be stored.
It may prove difficult or even impossible to convert 2 Double's to a single double that can reliably then be converted to 2 Double's.
For example (a simple and probably impractical example) if the highest value possible for lat and lon were 1000, then you could have, an algorithm, something like:-
@TypeConverter
fun fromCord(cord: Coord): Double {
return cord.lat + (cord.lon * 1000)
}
@TypeConverter
fun toCord(both: Double): Coord {
val lon = both / 1000
return Coord(both - lon, lon)
}
Then both values are available when extracting the data, as the single value stored is convertered from that value to the Coord, from which you can get the lat and lon values.
Typically objects are converted to a JSON representation of the object, which is a String (and hence can be stored in the database as a single column).
If you include com.google.code.gson as a dependency e.g. have implementation 'com.google.code.gson:gson:2.9.0' in the build gradle, then you could have the two Type Converters as:-
@TypeConverter
fun fromCoordToString(coord: Coord): String {
return Gson().toJson(coord)
}
@TypeConverter
fun fromStringToCoord(json: String): Coord {
return Gson().fromJson(json,Coord::class.java)
}
In which case, if the Coord had a lat of 100.123 and lon of -100.321 then the data stored in the coord column would be:-
{"lat":100.123,"lon":-100.321}
- i.e. a single String representation of the two values, but actually a representation of the Coord object, with the lat and lon values embedded.