Why is slice a possible language future feature?


#1

In the language future survey, the item 8 is “Slices for lists and arrays”.

I don’t really understand why would the language need enhancement while this would really easilly done by the stdlib:

operator fun <T> List<T>.get(r: IntRange) = subList(r.start, r.endInclusive + 1)
operator fun <T> List<T>.get(r: IntRange, step: Int) = subList(r.start, r.endInclusive + 1).filterIndexed { index, _ -> index % step == 0 }

fun main(args: Array<String>) {
    val list = listOf(0, 1, 2, 3, 4, 5)
    println(list[1..4])
    println(list[1 until 4])
    println(list[1..4, 2])
}

What would be the benefit of adding a new language syntax?


#2

Fully agree.

Why not?

println(list[1..4 step 2])

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.ranges/step.html


#4

Kotlin 1.0:

val list = listOf(0, 1, 2, 3, 4, 5)
println(list.slice(1 until 4 step 2))

#5

Array slices are extremely common in data manipulation code (see numpy/scipy in the Python world), so it may make sense to make it as easy as possible to use them in Kotlin as well.


#6

This looks really like the ternary operator debate.


#7

I created a little bunch of extensions for slicing compatible with 1.0
Obviously it doesn’t fit for all use cases but simple enough for me to use in little pet projects


#8

@yole I do not question the need for the feature, which is obvious.

I question the need for a new language syntax!


#9

The key words in my reply are “as easy as possible”. In many cases, explicit syntax makes a feature easier to use than the application of a library feature.


#10

#11

Yeah, but why our code must be verbose when it can be concise?
Also, Kotlin is powerful enough to create another DSL for slicing, something like this:


or this:

And yes, it can be unclear at first, but simple and special enough to become familiar after 5 minutes of coding.


#12

Yes, special built-in syntax for common feature is good, but adding ad-hoc syntax for list and array slicing only seems as overkill
For example: You can provide a new operators:


#13

+1 for new operators. It could open new possibilities/use cases.


#14

Why don’t show those?

file.exist() : { file.delete() } ?: throw FileNotFoundException()

val list = item1 : item2 : item3

However I am curious to know about new operator, something like:

operator fun Int.colon(other: Int) = this until other
operator fun IntProgression.colon(other: Int) = this step other