SIR*_*IRS 1 kotlin kotlin-extension
我可以有 kotlin 扩展函数来做这样的事情吗:
// extension
inline fun <T : Any> T?.runIfNotNull(function: (T) -> Unit) {
this?.let { function(it) }
}
// some function
fun doSomething(int: Int){
// do something
}
// doSomething will be called with maybeNullInt as argument,
// when maybeNullInt is not null
maybeNullInt?.runIfNotNull { doSomething }
Run Code Online (Sandbox Code Playgroud)
基本上,我想要的是替换
maybeNullInt?.let{ doSomething(it) }
Run Code Online (Sandbox Code Playgroud)
和
maybeNullInt?.runIfNotNull { doSomething }
Run Code Online (Sandbox Code Playgroud)
let您可以使用Kotlin 标准库中的函数,而不是创建自己的扩展函数:
maybeNullInt?.let(::doSomething)
Run Code Online (Sandbox Code Playgroud)
::- 在 Kotlin 中,我们使用此运算符按名称引用函数。
| 归档时间: |
|
| 查看次数: |
284 次 |
| 最近记录: |