为什么myDayForecast.map不是空的?
我创建一个对象myDayForecast与二次建设,我认为var bb将是空的,因为传递到主要建设的二次施工parmater是HashMap()。 我看到一些关于HashMap()的文档,它将返回空。
但是在我运行代码后,我发现var bb不是空的(你可以看到图像),为什么?
var myDayForecast= DayForecast(15L,"Desciption",10,5,"http://www.a.com",10L) var bb=myDayForecast.map 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 } }
结果图像
在最后如果第二个构造函数定义行:
constructor(date: Long, description: String, high: Int, low: Int, iconUrl: String, cityId: Long) : this(HashMap()) {
: this(HashMap())
是对主构造函数的调用:
DayForecast(var map: MutableMap<String, Any?>)
但是以一个空的HashMap作为参数。
所以当你打电话时:
var myDayForecast=DayForecast(15L,"Desciption",10,5,"http://www.a.com",10L)
发生的第一件事情之一是用上面提到的空HashMap调用主构造函数。
这就好像你调用了这样的主构造器:
DayForcast(map = HashMap())
所以现在map已经被设置为一个空的HashMap了。
在第二个构造函数中,每个字段都用map
标记,其中map
是DayForecast的MutableMap属性。 如下所示:
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 ... }
这意味着对这些字段的任何访问都被委托给map
引用的对象,在这种情况下,它是一个MutableMap
对象。 对于一个MutableMap对象来说,这意味着编译器会将诸如this.date = 15L
这样的调用翻译成像this.map.put(“date”,15L)这样的引用,像blah = this.date
这样的引用将被翻译成类似的东西, blah = this.map.get("date")
接下来,在主构造函数被调用后,第二个构造函数的第二部分被运行。
this.date = date this.description = description this.high = high this.low = low this.iconUrl = iconUrl this.cityId = cityId
现在,因为每个属性都被声明为var propXYZ by map
所有这些调用都被转换为像this.map.put("date", date)
这样的调用,它将用空值填充最初的空HashMap,你打电话的时间
var bb=myDayForecast.map
,map现在是一个填充HashMap。
如果这仍然令人困惑,请查看Kotlin文档的delegate-properties部分。
你正在使用地图来存储你的财产数据 。 这是通过by map
和工作获取和设置。 通过为属性赋值,可以将元素添加到地图中。 所以最初你的HashMap
是空的,但是在构造函数的最后,你已经隐式地给它添加了值。 Kotlin不创建另外的字段或机制来存储值,否则。