Frank Neblung
Frank Neblung

Reputation: 3175

Why does kotlin not allow null-safe indexing operator?

We are used to the indexing operator when accessing Maps.

fun fun1(map: Map<*, *>) {
    assert(map.get("key") === map["key"])
}

But why can the indexing operator not be used for nullable Map? The following code does not compile.

fun fun2(map: Map<*, *>?) {
    assert(map?.get("key") === map?["key"])
}
                                  ^^^ 

Upvotes: 6

Views: 1663

Answers (1)

Enselic
Enselic

Reputation: 4912

Why does kotlin not allow null-safe indexing operator?

The reason you can not use map?.[K] is because that is not supported syntax. This is a long-standing feature request. Here is a 4 year old issue for it: https://youtrack.jetbrains.com/issue/KT-8799

Use the equivalent method syntax instead, which is map.get(T) instead of map[T], i.e. what you have first:

fun fun2(map: Map<*, *>?) {
    assert(map?.get("key") === map?.get("key"))
}

you can find in the official docs that .get() is what implements the [] operator. In other words, the compiler translates [] into .get() behind the scenes, so you might as well call it directly in this case.

Upvotes: 5

Related Questions