Recently I was working with lists in kotlin and had the following snippet:
a = listOf(1, 2, 3, 4)
println(a[-2])
Of course this causes an IndexOutOfBoundsException
so I thought it would be nice to extend this functionality. So I thought one could override the get
operator in the List
class:
operator fun <T> List<T>.get(index: Int): T =
// Here this should call the non-overridden version of
// get.
get(index % size)
I understand that extensions are just static methods and therefore cannot be overridden, but is there a way one can achieve something like this?
Of course you could just create another function
fun <T> List<T>.safeGet(index: Int): T = get(index % size)
but I'd like to know if there are other ways.
(I understand that index % size
is a very naive way of doing what I want, but it's not the focus of my question and makes the code smaller.)
EDIT
When I wrote this question I thought the %
operator would return always positive numbers when the right hand side is positive - like in python. I'm keeping the original question here just for consistency.