Can `slice(..)` please be an operator like in pyt...
# getting-started
u
Can
slice(..)
please be an operator like in python?
y
Why not use
get
? You can have it take 3 arguments
Or even better, just have it use the range:
Copy code
operator fun <T> List<T>.get(indices: IntRange): List<T> = slice(indices)
// usage
list[1..5]
list[1..10 step 2]
list[10 downTo 1]
u
whaa that works? although the implied ends are kind of important and ranges dont know that right (
2..end
)? but i guess
slice
literal has that problem as well
y
Yeah maybe you need a different way to represent those. Should still be doable somehow
u
well python syntax is
foo[2:]
, start is 0 always so obviously 0 is fine, but we need some literal for end
y
Here's a little something that can work:
Copy code
@JvmInline value class OpenEndedRange(val start: Int)
object End
val end: End = End
operator fun Int.rangeTo(end: End) = OpenEndedRange(this)
operator fun <T> List<T>.get(indices: OpenEndedRange): List<T> = slice(indices.start..lastIndex)
// usage
list[1..end]
It's a little over-engineered, so edit as desired
🤯 1
👀 1
u
neat
j
This is cool. If this were in the standard library I'd be pleased.
k
This is cool, but I'm suspicious of that public value called `end`; it's a very common name and could be used for all sorts of things in different places, and therefore prone to subtle bugs if there is a local Int variable called
end
(which could very easily be the case).
âž• 4
j
Didn't think it through that far - that would be quite the problem.
a
I guess a better solution for
end
would be to have an object like
Ranges
with properties
Ranges.start
,
Ranges.end
etc
âž• 1