Support Python-like negative indexes on indexed collections-like objects #52771
Labels
area-core-library
SDK core library issues (core, async, ...); use area-vm or area-web for platform specific libraries.
library-core
type-enhancement
A request for a change that isn't a bug
The decade-long issue #983 suggests adding Python-like slices to Dart. Although it's somewhat related with negative indexes in collections, and some commenters in the issue talked about it, I see it as a separate feature, and thus I'm opening another issue.
Basically, negative indexes works like regular indexes but starting at the end.
So, for instance, if I want to get the 2nd last element of a
List
, instead of usinglist[list.length - 2]
I could uselist[-2]
.This could be extended not only to
[]
but other methods, like sublist or substring:Note that, in addition to being shorter, in the second case we wouldn't have the need to bind the string to
str
, as we wouldn't have the need to access it's length.AFAIK this can already be implemented, as the
[]
operator on Lists/Strings already accept negative numbers, but throws aRangeError
in runtime, thus there's no need for changes in the language.Cons
A possible con is that when someone uses computed indexes, in many cases computing negative indexes would not be intended. Thus, the user would either have to manually check for negative indexes or it would result in a non-error in runtime that could pass unnoticed.
The text was updated successfully, but these errors were encountered: