gpt4 book ai didi

generics - Scala,高级泛型扩展

转载 作者:行者123 更新时间:2023-12-04 02:54:18 25 4
gpt4 key购买 nike

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

我总是收到错误:

class type required but 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);
}

}

最佳答案

A extends B写的是 A<:B在 Scala 中不是 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
}

关于generics - Scala,高级泛型扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4285510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com