【发布时间】:2018-12-29 21:10:54
【问题描述】:
以下代码来自“Kotlin for Android Developers”,您可以在https://github.com/antoniolg/Kotlin-for-Android-Developers访问它
为了在CityForecastTable.NAME 中插入一行数据,我必须通过源代码 fun SQLiteDatabase.insert 传递一个vararg 值
1:作者做了一个扩展toVarargArray()将MutableMap<String, Any?>转换为Pair<String, Any?>,不知道有没有更好的办法。我需要使用扩展功能吗?
2:作者必须在Code C中使用代码it.value!!,不知道代码fun <K, V : Any> Map<K, V?>.toVarargArray(): Array<out Pair<K, V?>> = map({ Pair(it.key, it.value) }).toTypedArray()对不对?
3:我不知道当我插入一个列包含空值的行数据时应用是否会崩溃。
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
}
}
代码 C
fun <K, V : Any> Map<K, V?>.toVarargArray(): Array<out Pair<K, V>> =
map({ Pair(it.key, it.value!!) }).toTypedArray()
源代码
fun SQLiteDatabase.insert(tableName: String, vararg values: Pair<String, Any?>): Long {
return insert(tableName, null, values.toContentValues())
}
【问题讨论】:
-
应用是否会崩溃不是很容易测试吗?