Kotlin Set to Null If Not Null

血红的双手。 提交于 2019-12-12 12:31:13

问题


Is there an idiom in Kotlin for setting a variable to null if it is not already null? Something more semantically pleasing than:

var test: String? = null
if(test != null) test = null

回答1:


You can use the execute if not null idiom:

test?.let { test = null }



回答2:


Just assign null to local variable:

test = null

In case if it's not null - you assign null to this variable. In case if variable is null - you just assign null to it, so nothing changed.




回答3:


I came up with this extensions which makes this simpler:

inline fun <T, R> T.letThenNull(block: (T) -> R): T? { block(this); return null }
val test: Any? = null
...
test = test?.letThenNull { /* do something with test */ }


来源:https://stackoverflow.com/questions/39583928/kotlin-set-to-null-if-not-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!