13 Lambdas
48
1
class ViewHolder(view: View, val itemClick: (Forecast) -> Unit)
The rest of the code remains unmodified. Just a last change to
MainActivity
:
1
val adapter = ForecastListAdapter(result) { forecast -> toast(forecast.date) }
We can simplify the last line even more. In functions that only need one parameter, we can make
use of the
it reference, which prevents us from defining the left part of the function specifically. So
we can do:
1
val adapter = ForecastListAdapter(result) { toast(it.date) }
13.3 Extending the language
Thanks to these transformations, we can create our own builders and code blocks. We’ve already
been using some interesting functions such as
with
. A simpler implementation would be:
1
inline fun
with(t: T, body: T.() -> Unit) { t.body() }
This function gets an object of type
T
and a function that will be used as an extension function. The
implementation just takes the object and lets it execute the function. As the second parameter of the
function is another function, it can be brought out of the parentheses, so we can create a block of
code where we can use
this
and the public properties and functions of the object directly:
1
with(forecast) {
2
Picasso.with(itemView.ctx).load(iconUrl).into(iconView)
3
dateView.text = date
4
descriptionView.text = description
5
maxTemperatureView.text = "$high"
6
minTemperatureView.text = "$low"
7
itemView.setOnClickListener { itemClick(this) }
8
}
Do'stlaringiz bilan baham: