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

Lukasz Kalnik

07/15/2022, 8:42 AM
Is there no smart cast in case of `OR`ed null checks inside of
if
?
Copy code
val selectedScene1: String? = // ...
val selectedScene2: String? = // ...
if (selectedScene1 != null || selectedScene2 != null) {
    val sceneToFind: String = selectedScene1 ?: selectedScene2!! // The !! are necessary to make this work
}
m

Michael de Kaste

07/15/2022, 8:47 AM
a combination based smartcast isn't really possible since the nullability of one now relies on the nullability of the other. What you however can do is something like
Copy code
listOfNotNull(selectedScene1, selectedScene2).firstOrNull() //on null, you're not in your 'if'. On value, you are.
l

Lukasz Kalnik

07/15/2022, 8:49 AM
Smart solution, thank you!
So the non-nullability in the line with
?:
cannot be resolved at compile time if I understand this correctly.
Although logically
sceneToFind
should always be non-nullable inside the
if
(even without the
!!
). But I suppose the nullability is resolved by type checker which doesn't follow the logic of the program but just statically compares resolved types.
e

ephemient

07/15/2022, 9:53 AM
if you remove
Copy code
if (selectedScene1 != null || selectedScene2 != null)
and replace it with
Copy code
val sceneToFind: String? = selectedScene1 ?: selectedScene2
if (sceneToFind != null) {
then you will get effectively the same result, but safely
l

Lukasz Kalnik

07/15/2022, 9:59 AM
True, that's also a good solution. 🙏