extension-methods - WeakReference的扩展方法

标签 extension-methods weak-references kotlin

我想创建扩展方法,仅当引用不为空时才会执行方法:

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()
}

关于extension-methods - WeakReference的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33854765/

相关文章:

mongodb - 允许记录类型 F# 为空

Swift:使用弱 self 在基于 block 的执行中保持原子性

android - 尝试在空对象引用上调用接口(interface)方法 'boolean com.google.common.util.concurrent.ListenableFuture.cancel(boolean)'

android - 这些 ifs 语句会降低性能吗?

vb.net - 通用扩展方法,List(Of T)

c# - 为什么不能为静态类创建扩展方法?

c# - 表达式定义说明

android - AsyncTask,如何在所有 UI 方法中正确使用 Wea​​kReference

java - 如何强制 JVM 清除 WeakHashMap 的所有 WeakReferences/keys

android - Kotlin:设置 TextView 时 lateinit 属性尚未初始化