我想创建扩展方法,只有在引用不为null时才执行方法:
fun WeakReference<T>.safe( body : T.() -> Unit) {
this.get()?.body()
}
用法示例:
mTimerView.safe({startTimer(time)})
// OR
mTimerView.safe { startTimer(time) }
而不是:
mTimerView.get()?.stopTimer()
我做错了什么因为我得到了:&#34;未解决的参考:T&#34; ?
或者没有扩展方法可能有更简单的方法吗?
答案 0 :(得分:3)
我找到了答案:
fun <T> WeakReference<T>.safe( body : T.() -> Unit) {
this.get()?.body()
}