上一篇文章中介绍了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对其演化,来说明这几个函数的用法和区别。
with函数
with函数传入对象可以直接调用对象的方法,返回是最后一行。
public inline fun <T, R> 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) }
}
apply函数
调用某对象的apply函数,在函数范围内,可以任意调用该对象的任意方法,并返回该对象。
public inline fun <T> 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) }
}
let函数
默认当前这个对象作为闭包的it参数,返回值是函数里面最后一行,或者指定return。
public inline fun <T, R> 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) }
}
run函数
调用指定的函数块,返回最后一行或者return相关内容。
public inline fun <T, R> 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) }
}