布景

啰嗦的多办法回调代码影响可读性,更影响读代码人的心境,以至于不想去保护.

简略栗子,我仅需求onTextChanged办法里履行打印. afterTextChanged 和 beforeTextChanged就是剩余的

    editText.addTextChangedListener(object : TextWatcher {
override fun afterapproveTextChanged(s: Editable?) {
}
override fun befo接口英文reTekotlin为什么流行不起来xtChanappearancegedkotlin是什么意思(s: CharSequence?接口测验的流程和步骤, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
log接口测验的流程和步骤d(content = "$s, $start, $before接口crc过错计数, $count");
}
})

实际工作的时分,或许远不止3个办法回调.还有很多这种接口混在一同的场景.

改善

简略结束空接口

    editText.addTextChangedListeneapproachr(object : TextWatcherEmptyImpl() {
override fun on接口和抽象类的区别TextChanged(s: CharSequence?, start: Int, before: Int, co接口类型unt: Int) {
logd(content = "$s, $sta接口的作用rt, $before, $count");
}
})

依托结束如下:

// 空结束
open class TextWatcherEmptyImpl : TextWatcher {
override fun afterTkotlin能替代java吗extChaapplenged(s: Editablappstoree?) {
}
override fun be接口英文foreTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
overr接口类型ide fun onTextChanged(s: CharSequence?, start: I接口crc过错计数nt, before: Inapplicationt, count: Int) {
}
}

Kot接口测验的流程和步骤lin闭包结束

   editText.addTextChangedListener {
onkotlin言语TextChanged { s, start, before, after ->
l接口的作用ogd(content = "$s,$start,$before,$after") }
}

依托完接口结如下:

// 支撑kotlin风格的扩approach展函数改写
fun EditText.addTextCha接口测验ngedListener(init: (TextWatcherKotlinImpl.() -> Unit)) =
this.addTextC接口hangedListener(
TextWatcherKotlinImpl().apply { init() }
)
// 支撑kotlin风格的回调改写
class TextWa接口是什么tcherKotlinImpl(
var beforeTextChanged: ((CharSequence?, Int, Int, Ikotlin怎样读nt) -> Unit)? = null,
var onTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)接口crc过错计数? = null,
var afterTextChangeappled: ((Editable?) -> Unit)? = null
) : TextWatcher {
override fuapproven beforeTextChanged(s: CharSequence?, start: Int, count: Int,approve after: Int) {
beforeTex接口和抽象类的区别tChanged?.invoke(s, starkotlin能替代java吗t, count, after)
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
onTextChanged?.invoke(s, start, before, count)
}
override fun afterTeapplextChanged(s: Editable?) {appstore
afterTextChanged?.invoke(s)
}
fun bkotlin能替代java吗eforeTextChanged(listener: ((CharSequence?, Int, Int, Int) -> Unit)) {
beforeTextChanged = listener
}
fun o接口英文nTextChanged(listener: ((CharSequence?, Int, Int, Int) -> Unit)) {
onTextChangapp装置下载ed = listener
}
f接口测验un afterTextChanged(listener: ((Editable?) -> Unit)) {
afterTextChange接口的作用d = listener
}
}

总结

便当记忆放一张图来对比下简练度

Kotlin回调多办法的调用代码变得简练