Scala,高级泛型扩展
我正在尝试将 https://gist.github.com/319827 重写为 Scala。但我无法编译它。正确的语法是什么?
我总是遇到错误:
需要类类型,但 java.util.Comparator[_ >: 找到 java.lang.Comparable[java.lang.Object]]
源:
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);
}
}
I'm trying to rewrite https://gist.github.com/319827 to Scala. But I can't compile it. What is the correct syntax?
Error I'm allways getting:
class type required but java.util.Comparator[_ >:
java.lang.Comparable[java.lang.Object]] found
source:
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
A extends B
在 scala 中被写成A<:B
而不是A>:B
顺便说一句,scala 类型系统足够强大,可以避免使用代码中的 Object(scala 中的 AnyRef)
A extends B
is writtenA<:B
in scala notA>:B
by the way, scala type system is powerful enough to avoid use of Object (AnyRef in scala) in your code
我以更多的经验回到了这个问题,并解决了它,尽管我认为这是可以更好。
I've returned to the problem with more experience and solved it, although I think that is can be better.
好吧,你把那个 java 版本弄乱了。请注意,您创建了一个 Comparator< 的实例。可比<对象>>然后用通配符将其分配给值 - 有何用处?您不会为该变量分配任何其他内容。更不用说您的 getInstance 还定义了通配符,而它返回相同 Comparator< 的所有内容。可比<对象>>
所以:
Well, you made some mess with that java version. Notice that you create an instance of Comparator< Comparable< Object>> and you assign it to value with wildcard - what for ? You won't assign anything else to that variable. Not talking that your getInstance also defines wildecards, while it returns everything the same Comparator< Comparable< Object>>
So: