myanmarking
09/09/2021, 10:29 AMRuckus
09/09/2021, 2:21 PMlist[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:
list[it % list.size]
// or (to also gracefully handle negative indices)
list[it.mod(list.size)]
Ruckus
09/09/2021, 2:28 PMTobias Berger
09/09/2021, 3:37 PMTobias Berger
09/09/2021, 3:40 PMfun <T> List<T>.getMod(index: Int) = this.takeIf { it.isNotEmpty() }?.let { get(index % size) }
Tobias Berger
09/09/2021, 3:41 PMfun <T> List<T>.getMod(index: Int) = if (isEmpty()) null else get(index % size)
myanmarking
09/09/2021, 3:42 PM