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)
r
No, but it's not that hard to implement yourself. Just make sure to keep in mind the edge case where the list is empty. As far as how to implement the non empty logic, it depends on what you mean by "go back to zero". If you mean anything outside the list bounds will return the fist element:
Copy code
list[if (it in list.indices) it else 0]
// or
if (it in list.indices) list[it] else list.first()
If you mean you want anything outside the bounds to "loop around", it's even easier:
Copy code
list[it % list.size]
// or (to also gracefully handle negative indices)
list[it.mod(list.size)]
(Note in the looping case, if the size is 3, getting 4 will get index 1, not 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