The following code is from "Kotlin for Android Developers", you can access it at https://github.com/antoniolg/Kotlin-for-Android-Developers
In order to insert a row data into CityForecastTable.NAME
, I have to pass a vararg
values by Source Code fun SQLiteDatabase.insert
1: The author make a extension toVarargArray()
to convert a MutableMap<String, Any?>
to Pair<String, Any?>
, I don't know whether there is a better way to do that. Do I need to use a extension function?
2: The author have to use the code it.value!!
in Code C , I don't know if the code fun <K, V : Any> Map<K, V?>.toVarargArray(): Array<out Pair<K, V?>> = map({ Pair(it.key, it.value) }).toTypedArray()
is right?
3: I don't know whether the app will crash when I insert a row data of which a column include null value.
import org.jetbrains.anko.db.*
class ForecastDb(private val forecastDbHelper: ForecastDbHelper = ForecastDbHelper.instance,
private val dataMapper: DbDataMapper = DbDataMapper()) : ForecastDataSource {
fun saveForecast(forecast: ForecastList) = forecastDbHelper.use {
//dataMapper.convertFromDomain(forecast) will return CityForecast object
with(dataMapper.convertFromDomain(forecast)) {
insert(CityForecastTable.NAME, *map.toVarargArray())
}
}
}
class CityForecast(val map: MutableMap<String, Any?>, val dailyForecast: List<DayForecast>) {
var _id: Long by map
var city: String by map
var country: String by map
constructor(id: Long, city: String, country: String, dailyForecast: List<DayForecast>)
: this(HashMap(), dailyForecast) {
this._id = id
this.city = city
this.country = country
}
}
Code C
fun <K, V : Any> Map<K, V?>.toVarargArray(): Array<out Pair<K, V>> =
map({ Pair(it.key, it.value!!) }).toTypedArray()
Source Code
fun SQLiteDatabase.insert(tableName: String, vararg values: Pair<String, Any?>): Long {
return insert(tableName, null, values.toContentValues())
}