Function invocation
a(i)
a.invoke(i)
a(i, j)
a.invoke(i, j)
a(i_1, …, i_n)
a.invoke(i_1, …, i_n)
11.2 The example
As you can imagine, Kotlin lists have the array-like operations implemented, so we can access to list
items the same way we’d do in Java arrays. But it goes beyond: in mutable lists, the item can also
be set directly in a very simple way:
1
val x = myList[2]
2
myList[2] = 4
If you remember, we have a data class called
ForecastList
, which basically consists of a list with
some extra info. It’d be interesting to access its items directly instead of having to request its internal
11 Operator overloading
40
list to get an item. On a totally unrelated note, I’m also going to implement a
size()
function, which
will simplify the current adapter a little more:
1
data class ForecastList(val city: String, val country: String,
2
val dailyForecast: List) {
3
operator fun get(position: Int): Forecast = dailyForecast[position]
4
fun size(): Int = dailyForecast.size
5
}
It makes our
onBindViewHolder
a bit simpler:
1
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
2
with(weekForecast[position]) {
3
holder.textView.text = "$date - $description - $high/$low"
4
}
5
}
As well as the
getItemCount()
function:
1
override fun getItemCount(): Int = weekForecast.size()
11.3 Operators in extension functions
We don’t need to stick to our own classes, but we could even extend existing classes using extension
functions to provide new operations to third party libraries. For instance, we could access to
ViewGroup
views the same way we do with lists:
1
operator fun ViewGroup.get(position: Int): View
2
= getChildAt(position)
Now it’s really simple to get a view from a
ViewGroup
by its position:
1
val container: ViewGroup = find(R.id.container)
2
val view = container[2]
Do'stlaringiz bilan baham: |