is there any std fun on Lists, than when getting b...
# random
m
is there any std fun on Lists, than when getting by index, if the index is greater than size, it will go back to zero? For instance, size: 3, get(4) will be the same as get(0)
t
To me, this case seems like a bit of a design issue. I think the index should somehow be validated/manipulated before accessing the list. There is no function for that, but you could add an extension function that uses mod operator on the index
like this:
Copy code
fun <T> List<T>.getMod(index: Int) = this.takeIf { it.isNotEmpty() }?.let { get(index % size) }
or (alternative notation)
Copy code
fun <T> List<T>.getMod(index: Int) = if (isEmpty()) null else get(index % size)
m
ya, i made one myself thanks! Just asked, because was not sure if there is already one