Reputation: 9424
When I have a nullable array/list/hashmap such as
var x: ArrayList<String>? = null
I know can access the element at index 1 like so
var element = x?.get(1)
or I could do it in a unsafe way like this
var element = x!![1]
but why can't I do something like this
var element = x?[1]
what's the difference between getting elements from an array using the first example and the last example, and why is the last example not allowed?
Upvotes: 2
Views: 47
Reputation: 89548
In the first example, you're using the safe call operator ?.
to call the get
function with it.
In the second example, you're using the []
operator on the non-nullable return value of the x!!
expression, which of course is allowed.
However, the language simply doesn't have a ?[]
operator, which would be the combination of the two. The other operators offered are also don't have null-safe variants: there's no ?+
or ?&&
or anything like that. This is just a design decision by the language creators. (The full list of available operators is here).
If you want to use operators, you need to call them on non-nullable expressions - only functions get the convenience of the safe call operator.
You could also define your own operator as an extension of the nullable type:
operator fun <T> List<T>?.get(index: Int) = this?.get(index)
val x: ArrayList<String>? = null
val second = x[2] // null
This would get you a neater syntax, but it hides the underlying null handling, and might confuse people who don't expect this custom extension on collections.
Upvotes: 3