Scala,高级通用扩展

时间:2010-11-26 13:07:31

标签: generics scala extending

我正在尝试将https://gist.github.com/319827重写为Scala。但我无法编译它。什么是正确的语法?

错误我总是得到:

  

需要类类型,但是java.util.Comparator [_>:   java.lang.Comparable [java.lang.Object]] found

来源:

package v6ak.util

import java.util.Comparator

object NaturalComparator extends Comparator[_ >: Comparable[Object]]{

    override def compare(o1:Comparable[Object], o2:Comparable[Object]) = {
        if( o1==null || o2==null ){
            throw new NullPointerException("Comparing null values is not supported!");
        }
        o1.compareTo(o2);
    }

}

3 个答案:

答案 0 :(得分:18)

A extends B在scala而不是A<:B

中写为A>:B

顺便说一句,scala类型系统足够强大,可以避免在代码中使用Object(在scala中为AnyRef)

package v6ak.util

import java.util.Comparator

class NaturalComparator[T <: Comparable[T]] extends Comparator[T] {
  override def compare(o1: T, o2: T) = {
    if (o1 == null || o2 == null) {
      throw new NullPointerException("Comparing null values is not supported!");
    }
    o1.compareTo(o2);
  }
}

object StringComparator extends NaturalComparator[String]

object Examples {
  StringComparator.compare("a", "b")
  StringComparator.compare(2, "b") // error
}

答案 1 :(得分:3)

嗯,你搞砸了那个java版本。请注意,您创建了Comparator的实例&lt;可比&LT;对象&gt;&GT;并使用通配符将其分配给值 - 用于什么?您不会为该变量分配任何其他内容。不是说你的getInstance也定义了wildecards,而它返回的是同一个Comparator&lt;可比&LT;对象&gt;&GT;

所以:

object NaturalComparator extends Comparator[Comparable[Object]]{
    override def compare(o1:Comparable[Object], o2:Comparable[Object]) = {
        if(o1 == null || o2 == null){
            throw new NullPointerException("Comparing null values is not supported!");
        }
        o1.compareTo(o2);
    }
}

答案 2 :(得分:2)

我已经回归到问题更多的经验和solved it,虽然我认为这可能会更好。

package v6ak.util

import java.util.Comparator

object NaturalComparator extends Comparator[Comparable[Any]]{

    def apply[T]() = asInstanceOf[Comparator[T]]

    override def compare(o1:Comparable[Any], o2:Comparable[Any]) = {
        if( o1 == null || o2 == null ){
            throw new NullPointerException("Comparing null values is not supported!")
        }
        o1 compareTo o2
    }

}