Kotlin 简化多回调函数
这里只是简单的例子,并没有实际意义,可以通过这个方法改造Android的TextWatcher ViewPager以及网络回调等各种多回调
"123".setXListener(object :XListener{
override fun onStart(name: String, time: String) {
}
override fun onProgress(progress: Int) {
}
override fun onEnd(path: String, time: Int) {
}
})
"123".setXlistenerHelpter {
OnStart { name, time ->
}
OnProgress {progress ->
}
OnEnd { path, time ->
}
}
源码
interface XListener {
fun onStart(name: String, time: String)
fun onProgress(progress: Int)
fun onEnd(path: String, time: Int)
}
class XListenerHelper : XListener {
private var tmpStart: ((String, String) -> Unit)? = null
private var tmpProgress: ((Int) -> Unit)? = null
private var tmpEnd: ((String, Int) -> Unit)? = null
override fun onStart(name: String, time: String) {
tmpStart?.invoke(name, time)
}
fun OnStart(start: (name: String, time: String) -> Unit) {
tmpStart = start
}
override fun onProgress(progress: Int) {
tmpProgress?.invoke(progress)
}
fun OnProgress(progress: (progress: Int) -> Unit) {
tmpProgress = progress
}
override fun onEnd(path: String, time: Int) {
tmpEnd?.invoke(path, time)
}
fun OnEnd(end: (path: String, time: Int) -> Unit) {
tmpEnd = end
}
}
fun String.setXListener(listener: XListener) {
}
fun String.setXlistenerHelpter(listener: (XListenerHelper.() -> Unit)) {
setXListener(XListenerHelper().apply { listener })
}