上一篇文章中介绍了RecycleView的Kotlin编程,在创建ViewHolder的时候有这么一段代码:
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(forecast: Forecast) {
itemView.tv_text1.text = forecast.date
itemView.tv_text2.text = forecast.high
itemView.tv_text3.text = forecast.low
itemView.tv_text4.text = forecast.notice
}
}
这篇文章将使用Kotlin高阶函数with,let,apply,run对其演化,来说明这几个函数的用法和区别。
public inline fun with(receiver: T, block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return receiver.block()
}
例如:with里面传入itemView对象,调用itemView的tv_text1,tv_text2……等方法,返回Unit类型数据。
fun bind(forecast: Forecast) = with(itemView) {
tv_text1.text = forecast.date
tv_text2.text = forecast.high
tv_text3.text = forecast.low
tv_text4.text = forecast.notice
setOnClickListener { itemClick(forecast) }
}
public inline fun T.apply(block: T.() -> Unit): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
block()
return this
}
例如:调用itemClick(forecast)对象的apply方法,并且返回itemClick(forecast)对象,他没有返回值,返回Unit。
fun bind(forecast: Forecast) = itemClick(forecast).apply {
itemView.tv_text1.text = forecast.date
itemView.tv_text2.text = forecast.high
itemView.tv_text3.text = forecast.low
itemView.tv_text4.text = forecast.notice
itemView.setOnClickListener { itemClick(forecast) }
}
public inline fun T.run(block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
例如:调用itemView的let方法,把itemView对象作为it使用,返回Unit。
fun bind(forecast: Forecast) = itemView.let {
it.tv_text1.text = forecast.date
it.tv_text2.text = forecast.high
it.tv_text3.text = forecast.low
it.tv_text4.text = forecast.notice
it.setOnClickListener { itemClick(forecast) }
}
public inline fun T.run(block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
例如:
fun bind(forecast: Forecast) = run {
itemView.tv_text1.text = forecast.date
itemView.tv_text2.text = forecast.high
itemView.tv_text3.text = forecast.low
itemView.tv_text4.text = forecast.notice
itemView.setOnClickListener { itemClick(forecast) }
}