Hacking with Kotlin: ranges

var array = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var subarray = array[3..5]; // The selected items: 3, 4
val list = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val list = (0..10).toList()
println(list.subList(3, 5)) // [3, 4]
println(list.subList(3..5)) // Doesn't compile yet
fun <E> List<E>.subList(range: ClosedRange<Int>): List<E> {
return this.subList(range.start, range.endInclusive)
}
println(list.subList(3..5)) // [3, 4]
println(list[3..5]) // Doesn't compile yet
operator fun <E> List<E>.get(range: ClosedRange<Int>): List<E> {
return this.subList(range)
}
operator fun <E> List<E>.get(range: ClosedRange<Int>) = this.subList(range)
println(list[3..5]) // [3, 4]

Solutions Architect @Depop, author of “Hands-on Design Patterns with Kotlin” book and “Web Development with Kotlin” course

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store