Does anyone know a better way of doing this type o...
# announcements
s
Does anyone know a better way of doing this type of thing? using
!!
always makes me feel icky
Copy code
val x: Int? = getAnIntegerOrMaybeANullFromAPlaceO
if (x != null) {
    functionThatTakesNonNullableIntegerArgument(x) // won't compile because it thinks x is nullable
    functionThatTakesNonNullableIntegerArgument(x!!) // will compile because added !!
} else {
    // handle the null case
}
s
I guess
var x
is a property, not a local variable. If so, do
Copy code
x?.let {
    functionThatTakesNonNullableIntegerArgument(it)
} ?: theNullCase()
p
x?.let { functionThatTakesNonNullableIntegerArgument(it) } ?: theNullCase() theNullCase() - can happen if function functionThatTakesNonNullableIntegerArgument(it) return null , but it is not of original code semantics
s
💯 thanks!!
p
x?.let { functionThatTakesNonNullableIntegerArgument(it) 1 } ?: theNullCase()
if result is not needed
d
This is only necessary if
x
has a custom getter or it is mutable
d
Could use a method reference here instead maybe to tidy up?