为Dart写sortBy函数

问题描述 投票:0回答:2

我正在尝试编写一个实用程序函数,该函数按给定属性对列表进行排序:

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)));

[例如,当属性为int时遇到问题

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

我收到编译错误:

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

为什么int不是Comparable?还有没有其他写sortBy的方法,以便它既可以在int上也可以在Comparable上使用?

sorting dart comparable
2个回答
1
投票

int确实实现了Comparable,但是实现了Comparable<num>,这是您的问题,因为您要检查Comparable<int>。您不可以像这样定义sortBy吗?

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)));

这似乎可行,因为我们现在只想确保U扩展Comparable


0
投票

Soon Dart将支持静态扩展方法。通过此功能,您可以使用一些现成的扩展程序。

示例:

import 'package:enumerable/enumerable.dart';

void main(List<String> args) {
  final sorded = ['apple', 'ball', 'cow'].orderBy((e) => e.length);
  print(sorded);
}

结果:

(cow, ball, apple)

© www.soinside.com 2019 - 2024. All rights reserved.