Skip to content

Add C#-style extension methods #13

Closed
@DartBot

Description

@DartBot

This issue was originally filed by [email protected]


Unless I'm reading the spec and examples wrong, it looks as if Dart uses the horrific Java approach of providing utility methods that operate on a interface, by putting them as static methods within some class with a name like 'Arrays' or 'Collections'. This is nonsense, especially when Linq and extension methods in C# have demonstrated a far superior approach, and Dart should provide an equivalent mechanism.

An obvious, easy way to add this would be that top level functions can optionally be called on an object using the dot operator, in which case the calling instance is passed as the first function parameter.

E.g. to write a generic first method that operates over an iterator for a supplied predicate:

T first<T>(Iterator<T> iterator, bool predicate(T obj)) {
    while (iterator.hasNext()) {
        if (predicate(iterator.next()) {
            return true;
        }
    }
    return false;
}

This could be called on an instance of an iterator as follows:

var jon = peopleIterator.first((p) => p.name == 'Jon');

Using extension methods that also return iterators, they can then chained together to form fluent expressions:

var fiveOldestJons = peopleInterator.where((p) => p.name == 'Jon').orderBy((p) => p.age).take(5);

It's worrying looking through the language design that you don't seem to looked much beyond JavaScript and Java for your inspiration in Dart. I can't speak for users of other languages, but I strongly doubt C# developers will be particularly impressed by a lot of the Java style anachronisms, and I'd urge you to cast your net a little more widely in general.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).closed-not-plannedClosed as we don't intend to take action on the reported issuetype-enhancementA request for a change that isn't a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions