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);
}
}
A extends B
is written A<:B
in scala not A>:B
by the way, scala type system is powerful enough to avoid use of Object (AnyRef in scala) in your code
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
}
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:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With