https://kotlinlang.org logo
#announcements
Title
# announcements
s

sonofblip

07/19/2019, 7:14 PM
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

streetsofboston

07/19/2019, 7:16 PM
I guess
var x
is a property, not a local variable. If so, do
Copy code
x?.let {
    functionThatTakesNonNullableIntegerArgument(it)
} ?: theNullCase()
p

PHondogo

07/19/2019, 7:18 PM
x?.let { functionThatTakesNonNullableIntegerArgument(it) } ?: theNullCase() theNullCase() - can happen if function functionThatTakesNonNullableIntegerArgument(it) return null , but it is not of original code semantics
s

sonofblip

07/19/2019, 7:19 PM
💯 thanks!!
p

PHondogo

07/19/2019, 7:19 PM
x?.let { functionThatTakesNonNullableIntegerArgument(it) 1 } ?: theNullCase()
if result is not needed
d

Dico

07/19/2019, 7:23 PM
This is only necessary if
x
has a custom getter or it is mutable
d

dave

07/20/2019, 7:57 AM
Could use a method reference here instead maybe to tidy up?
3 Views