Smart cast on collection

How to make the following code more concise?

nodes : List<Int>? = listOf(1, 2, 3)
if (nodes != null)  nodes[0] else null

Something like the following would be great, but it doesn’t seem to be supported right now.
nodes?[0]

nodes?.get(0)
1 Like

Thank you!

http://kotlinlang.org/docs/reference/operator-overloading.html

1 Like

With the operator overloading, we can actually do this:

operator fun<T> List<T>?.get(index : Int): T? {
    return this?.get(index)
}
val nodes: List<Int>? = listOf(1, 2, 3)
nodes[0]

I don’t know whether it’s good or bad. This is more concise. But I think there must be a reason why it’s not in the standard library.

I think the reason is that you would no longer see that nodes can be null at this point. It would just make it harder for someone reading the code to understand it. And how often would you actually use this? The only time I can think of is if you just want to access the first element and than you can just write nodes?.get(0).
It’s not like you can try to iterate it as you no longer now the length of the list :slight_smile:

1 Like