Search code examples
sortingdartcomparable

Writing a sortBy function for Dart


I'm trying to write a utility function that sorts a list by a given property:

List<T> sortBy<T, U extends Comparable<U>>(List<T> items, U Function(T item) f) =>
    items.toList()..sort((item1, item2) => f(item1).compareTo(f(item2)));

I've run into a problem when the property is an int, e.g.

sortBy<String, int>(['apple', 'ball', 'cow'], (word) => word.length);

I get a compilation error:

error: 'int' doesn't extend 'Comparable<int>'.

Why is int not Comparable? Is there another way to write sortBy so that it works on int as well as Comparable's?


Solution

  • int does implement Comparable but implements Comparable<num> which is your issue since you want to check for Comparable<int>. Could you not just define sortBy like this?

    List<T> sortBy<T, U extends Comparable>(List<T> items, U Function(T item) f) =>
        items.toList()..sort((item1, item2) => f(item1).compareTo(f(item2)));
    

    This seems to work since we now just want to ensure U extends Comparable.