Will something like this won’t work for templating?
abstract class Converters<T> {
@TypeConverter
fun mapListToString(value: List<T>): String {
val gson = Gson()
val type = object : TypeToken<List<T>>() {}.type
return gson.toJson(value, type)
}
@TypeConverter
fun mapStringToList(value: String): List<T> {
val gson = Gson()
val type = object : TypeToken<List<T>>() {}.type
return gson.fromJson(value, type)
}
}
// create
class UserConverter : Converters<User>()
// usage
@TypeConverters(UserConverter::class)
abstract class TestDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
or from the current example what if I do
@TypeConverter
fun <T> mapStringToList(inputString: String): List<T> {
val array = inputString
.split(strSeparator.toRegex())
.dropLastWhile { it.isEmpty() }
.toTypedArray()
val result = mutableListOf<T>()
val gson = Gson()
// 👇 ----
val type = object : TypeToken<List<T>>() {}.type
// ----
return array.fold(result) { acc, item ->
acc.add(gson.fromJson(item, type))
acc
}
}