Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Mainly a proof of concept. There are better ways to do this, but it was a quick experiment to create something like Python’s slicing in Kotlin.
import kotlin.math.min
object start {
infix fun to(other: Int) = RangeTuple(0, other)
infix fun to(other: end) = RangeTuple(0, Int.MAX_VALUE)
}
object end
infix fun Int.to(other: end) = RangeTuple(this, Int.MAX_VALUE)
class RangeTuple(val first: Int, val last: Int)
fun <T> effectiveIndex(index: Int, list: List<T>): Int {
return min(list.size, if (index < 0) list.size + index else index)
}
operator fun <T> List<T>.get(range: RangeTuple): List<T> {
return this.subList(effectiveIndex(range.first, this), effectiveIndex(range.last, this))
}
infix fun Int.to(other: Int): RangeTuple {
return RangeTuple(this, other)
}
fun main() {
val list = listOf(1, 2, 3, 4)
println(list[1 to 3]) // [2, 3]
println(list[0 to -1]) // [1, 2, 3]
println(list[-2 to -1]) // [3]
println(list[start to end]) // [1, 2, 3, 4]
println(list[start to 3]) // [1, 2, 3]
println(list[-2 to end]) // [3, 4]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.