HashMap(它)会做什么?
我正在学习有关“Android开发人员的Kotlin”示例代码https://github.com/antoniolg/Kotlin-for-Android-Developers
在代码.parseList { DayForecast(HashMap(it)) }
,我不明白什么函数HashMap(它)会做。 HashMap()是一个类,接受一个parmater吗?
而且,我认为DayForecast(...)..
类的完整代码是代码A,对不对?
再次,如果我创建一个对象var myDayForecast=DayForecast(10L,"Desciption",10,5,"http://www.a.com",10L)
,myDayForecast.map将是空的,对吗?
代码A
class DayForecast(var map: MutableMap<String, Any?>) { var _id: Long by map var date: Long by map var description: String by map var high: Int by map var low: Int by map var iconUrl: String by map var cityId: Long by map constructor(date: Long, description: String, high: Int, low: Int, iconUrl: String, cityId: Long) : this(map: MutableMap<String, Any?>=HashMap()) { this.date = date this.description = description this.high = high this.low = low this.iconUrl = iconUrl this.cityId = cityId } }
原始代码
override fun requestForecastByZipCode(zipCode: Long, date: Long) = forecastDbHelper.use { val dailyRequest = "${DayForecastTable.CITY_ID} = ? AND ${DayForecastTable.DATE} >= ?" val dailyForecast = select(DayForecastTable.NAME) .whereSimple(dailyRequest, zipCode.toString(), date.toString()) .parseList { DayForecast(HashMap(it)) } val city = select(CityForecastTable.NAME) .whereSimple("${CityForecastTable.ID} = ?", zipCode.toString()) .parseOpt { CityForecast(HashMap(it), dailyForecast) } city?.let { dataMapper.convertToDomain(it) } } class DayForecast(var map: MutableMap<String, Any?>) { var _id: Long by map var date: Long by map var description: String by map var high: Int by map var low: Int by map var iconUrl: String by map var cityId: Long by map constructor(date: Long, description: String, high: Int, low: Int, iconUrl: String, cityId: Long) : this(HashMap()) { this.date = date this.description = description this.high = high this.low = low this.iconUrl = iconUrl this.cityId = cityId } }
我想从这里的答案,你应该已经知道,parseList提供了一个Map
对象的封闭{ DayForecast(HashMap(it)) }
。
但是现在你展示了DayForecast
的定义
class DayForecast(var map: MutableMap<String, Any?>)
需要一个MutableMap
MutableMap
和Map
之间的主要区别是Map
不能改变,而MutableMap
可以改变。
DayForecast
需要一个MutableMap
的原因是因为在二级构造函数中,被传入的对象(被称为map
被改变(变异)。 这是你最近的其他问题的一部分 。
HashMap是一个基于Hash表格的MutableMap
接口实现,所以可以使用MutableMap
。
所以总结一下:
DayForecast()期望一个MutableMap
对象被传递给它的主要构造函数,但是parseList只提供一个Map
给它所接收的闭包,所以解决方案是插入HashMap()
来创建一个MutableMap
。
这也应该回答你在评论中提出的问题,为什么不能parseList只是{ DayForecast(it) }
而不是{ DayForecast(HashMap(it)) }
? 这是因为如上所示,DayForecast()的构造函数需要一个MutableMap
, it
不是(它是一个Map
),而HashMap(it)
是一个MutableMap
。
我不明白
HashMap(it)
会做什么功能。HashMap()
是一个类并接受一个参数吗?
从HashMap(Map)
的文档 :
使用与指定的
Map
相同的映射构造一个新的HashMap
。HashMap
是使用默认加载因子(0.75)和足以容纳指定映射中的映射的初始容量创建的。
为了回答你的问题:是的, HashMap
是一个类,它接受it
需要是一个Map
实例的参数。