弱引用的扩展方法
我想要创建扩展方法,只有当引用不为null时才会执行方法:
fun WeakReference<T>.safe( body : T.() -> Unit) { this.get()?.body() }
用法示例:
mTimerView.safe({startTimer(time)}) // OR mTimerView.safe { startTimer(time) }
代替:
mTimerView.get()?.stopTimer()
我做错了,因为我得到:“未解决的参考:T”?
或者,也许没有扩展方法有更简单的方法呢?
我找到了答案:
fun <T> WeakReference<T>.safe( body : T.() -> Unit) { this.get()?.body() }