Why Isn't Mydayforecast.map Empty?
Solution 1:
You're using a map to store your property data in it. This is done via by map
and works for getting and setting. By assigning a value to the properties you add elements to the map. So initially your HashMap
is empty, but at the end of the constructor, you've added values to it implicitly. Kotlin doesn't create another field or mechanism to store the values otherwise.
Solution 2:
In at the end if the secondary constructor definition line:
constructor(date: Long, description: String, high: Int, low: Int, iconUrl: String, cityId: Long)
: this(HashMap()) {
: this(HashMap())
is a call to the primary constructor:
DayForecast(var map: MutableMap<String, Any?>)
but with an empty HashMap as the argument.
So when you make the call :
var myDayForecast=DayForecast(15L,"Desciption",10,5,"http://www.a.com",10L)
one of the first things that happens is that the primary constructor is called with the empty HashMap as noted above.
This is as if you called the primary constructor like this:
DayForcast(map = HashMap())
So now map has been set to an empty HashMap.
In the secondary constructor, each of the fields are marked with by
map
, where map
is a MutableMap property of DayForecast. as seen here:
classDayForecast(var map: MutableMap<String, Any?>) {
var _id: Longby map
var date: Longby map
var description: String by map
var high: Intby map
var low: Intby map
var iconUrl: String by map
var cityId: Longby map
...
}
This means that any access to those fields is delegated to the object referred to by map
, which in this case is a MutableMap
object. For a MutableMap object this means that the compiler will translate calls such as this.date = 15L
into something like this this.map.put("date", 15L) and references like blah = this.date
will be translated into something like, blah = this.map.get("date")
Next, after the primary constructor has been called, the second part of the secondary constructor is run.
this.date = date
this.description = description
this.high = high
this.low = low
this.iconUrl = iconUrl
this.cityId = cityId
Now since each of these properties are declared as var propXYZ by map
each of these calls are translated into calls like this.map.put("date", date)
, which will fill in the initially empty HashMap with values, so that by the time you call
var bb=myDayForecast.map
, map is now a filled in HashMap.
Please take a look at the delegate-properties section of the Kotlin documentation, if this is still confusing.
Post a Comment for "Why Isn't Mydayforecast.map Empty?"