Why is slice a possible language future feature?

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 until 4])
    println(list[1..4, 2])

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


Fully agree.

Why not?

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

Kotlin 1.0:

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

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.


This looks really like the ternary operator debate.


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


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

I question the need for a new language syntax!

1 Like

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.

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.

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:


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

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
1 Like

Really? I thought that was the main selling point which convinced me to switch to Kotlin. Not only was sold several times in multiple talks esp. comparing it with Java but also the kotlin website has it as the first selling point under the “Why Kotlin?” section: “Concise”. I’m confident that generally means lesser code. Also, I don’t think the ternary operator would conflict with kotlin’s existing language features–it would enhance it as ternary operator looks a lot like some of the operators kotlin already has.

Really :wink:

1 Like