我正在https://github.com/antoniolg/Kotlin-for-Android-Developers学习有关《 Kotlin for android developers》的示例代码。

在代码.parseList { DayForecast(HashMap(it)) }中,我无法理解HashMap(it)函数的作用。 HashMap()是类并且接受参数it吗?

而且,我认为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
    }
}

最佳答案

我认为从答案here,您应该已经了解parseList为闭包{ DayForecast(HashMap(it)) }提供了Map对象。

但是,正如您现在显示的DayForecast的定义

class DayForecast(var map: MutableMap<String, Any?>)

需要MutableMap

MutableMapMap之间的主要区别在于,不能更改Map,而可以更改MutableMap

DayForecast需要MutableMap的原因是因为在辅助构造函数中,传入的对象(称为map)被更改(变异)。这是您其他近期question的一部分。

HashMapMutableMap接口的基于哈希表的实现,因此可以在需要MutableMap的情况下使用。

总结一下:

DayForecast()希望将MutableMap对象传递给它的主构造函数,但是parseList仅为其接收的闭包提供Map,因此解决方案是插入HashMap()来创建MutableMap

这也应该回答您在评论中提出的问题,为什么parseList不能仅使用闭包{ DayForecast(it) }而不是{ DayForecast(HashMap(it)) }?这是因为如上所示,DayForecast()的构造函数期望一个MutableMap,而itMap时,HashMap(it)不是(它是MutableMap)。

10-07 23:55