kotlinkotlin-null-safety

?. operator on a nullable array


I have a method which returns an array, on with I check that a certain index is set. In Java, I would do:

if (obj.method() != null && obj.method()[some_index] != null) {
   ...
}

Is it possible to shorten this in Kotlin with the ?. operator?

The following non-functional pseudo-code gives an idea what I am after:

if (obj.method()?.[some_index]) {
   ...
}

Solution

  • Yes, we can shorten this by replacing the operator with its equivalent function call:

    if (obj.method()?.get(some_index) != null)
    

    If we need to access the value from the array if it exists and isn't null, we can additionally use let:

    obj.method()?.get(some_index)?.let {
        println(it) // `it` is the value
    }