https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

Rajkumar Singh

01/20/2022, 10:55 PM
is there more Kotlin-y idiomatic way(s) to express the following code snippet:
val exitProcessing: Boolean? = func2call(tId, fId)
if (exitProcessing == null || exitProcessing == true) return
j

Joffrey

01/20/2022, 11:01 PM
If it makes sense to avoid returning null from the function in the first place, I'd consider that first. For instance, if
true
makes sense as a default value for
func2call
, it'd be better if it returned
true
instead of null. If that doesn't make sense (if it's useful to distinguish null from true), then you could express the default with the elvis operator at the call site:
Copy code
val exitProcessing = func2call(tId, fId) ?: true
if (exitProcessing) return
Or directly return from elvis in addition to the `if`:
Copy code
val exitProcessing = func2call(tId, fId) ?: return
if (exitProcessing) return
Although that one might be harder to read/understand
e

ephemient

01/20/2022, 11:29 PM
Copy code
exitProcessing != false
is preferred over
Copy code
exitProcessing ?: true
by the style guide: https://kotlinlang.org/docs/idioms.html#nullable-boolean
1
j

Joffrey

01/20/2022, 11:34 PM
I think what you refer to is rather this: https://kotlinlang.org/docs/coding-conventions.html#nullable-boolean-values-in-conditions But I believe this advice is about the content of a condition, where
if (exitProcessing ?: true)
would feel weird. Here I'm suggesting using elvis for the variable assignment, not in the condition
r

Rajkumar Singh

01/20/2022, 11:57 PM
@Joffrey I modified the func2call to return Boolean and that solved the whole null-dealing drama 🥂. thanks @Joffrey and @ephemient for the good discussion.
1
👍 2
4 Views