我一直在阅读 Scala 中的类型类,并认为自己掌握得很好,直到我想起了 Java 的java.util.Comparator
.
如果我理解正确,Ordering
是类型类的原型示例。Comparator
我能想到的 a和 an instance之间的唯一区别Ordering
是比较器必须是显式的,而排序可以并且通常是隐式的。
是Comparator
类型类吗?我得到的(错误的?)印象是 Java 实际上没有类型类。这是否意味着类型类需要能够是隐式的?我认为类型类的隐式转换主要是语法糖——尽管它很棒,但它“只是”给了编译器足够的提示——我错过了什么吗?
以下代码示例显示了如何Comparator
将排序操作添加到没有它的类型,而无需修改所述类型。
// Comparator used to retroactively fit the MyExample class with an ordering operation.
public static class MyExampleComparator implements Comparator<MyExample> {
public static final Comparator<MyExample> SINGLETON = new MyExampleComparator();
private MyExampleComparator() {}
public int compare(MyExample a, MyExample b) {
return a.value - b.value;
}
}
// Custom type, its only purpose is to show that Comparator can add an ordering operation to it when it doesn't
// have one to begin with.
public static class MyExample {
private final int value;
public MyExample(int v) {
value = v;
}
public String toString() {
return Integer.toString(value);
}
}
public static void main(String... args) {
List<MyExample> list = new ArrayList<MyExample>();
for(int i = 0; i < 10; i++)
list.add(new MyExample(-i));
// Sorts the list without having had to modify MyExample to implement an interface.
Collections.sort(list, MyExampleComparator.SINGLETON);
// Prints the expected [-9, -8, -7, -6, -5, -4, -3, -2, -1, 0]
System.out.println(list);
}