Why cant nullable arrays/hashmaps be accessed using []

Clash Royale CLAN TAG#URR8PPP
Why cant nullable arrays/hashmaps be accessed using
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?
1 Answer
1
In the first example, you're using the safe call operator ?. to call the get function with it.
?.
get
In the second example, you're using the operator on the non-nullable return value of the x!! expression, which of course is allowed.
x!!
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.
You can use Ctrl+click or Ctrl+B on
and you'll see that it jumps straight to the get function, so no, there is no difference between the two. (You can also check the bytecode, using the Show Kotlin Bytecode action)– zsmb13
Aug 7 at 18:18
get
Show Kotlin Bytecode
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thanks! Another thing i wanted to know was if I'm doing a x[1] would it compile at all differently from x.get(1) ?
– Quinn
Aug 7 at 18:17