Lilly
05/31/2022, 11:22 AMwhenNotNull
function:
inline fun <T : Any, R> whenNotNull(input: T?, callback: (T) -> R): R? = input?.let(callback)
usage:
override fun onReceive(context: Context?, intent: Intent?) {
whenNotNull(intent) {
it.someAction()
}
}
I have often problems with shadowed variable names, e.g. I cannot write:
override fun onReceive(context: Context?, intent: Intent?) {
whenNotNull(intent) { intent -> // shadowed
intent.someAction()
}
}
Is there some construct to recognize that intent
is not null within the callback
block, so I can write:
override fun onReceive(context: Context?, intent: Intent?) {
whenNotNull(intent) {
intent.someAction()
}
}
I have enabled some static analyzer tools which complain about the "it". I know I can just write whenNotNull(intent) { _intent -> }
but I'm curious if there is some Kotlin construct which targets this case.Landry Norris
05/31/2022, 1:31 PMLandry Norris
05/31/2022, 1:31 PMephemient
05/31/2022, 7:36 PMintent?.let {
intent.someAction()
}
is already smart-cast by contract, you don't need your own extensionephemient
05/31/2022, 7:38 PMif (intent != null) {}
to smart-castLilly
06/01/2022, 3:23 PMwhenNotNull
is more expressive. I found this on stackoverflow and thought this would be idiomatic. Maybe I will drop it for the simple constructs. What do you think? And would contracts help me to achieve the smart-cast contrac...haven't checked it out yet?ephemient
06/01/2022, 5:38 PM?.let
will give you that, and if you don't, then just use if
.
2. because of the null guard in ?.let
, it doesn't even need a contract to smart-cast to non-null within the lambda body, but yes contacts can be used in a custom extensionLilly
06/03/2022, 12:04 AMephemient
06/03/2022, 12:09 AMval maybe = intent?.let { ... }
because if you don't care about the result, just use a if
without an else