Scala, extended general extension

I am trying to rewrite https://gist.github.com/319827 on Scala. But I can not compile it. What is the correct syntax?

Mistake. I always get:

class type required, but java.util.Comparator [_>: java.lang.Comparable [java.lang.Object]] found

a 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); } } 
+6
generics scala
source share
3 answers

I went back to the problem with a lot of experience and solved it , although I think it could be better.

 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 } } 
+2
source share

A extends B written A<:B in scala not A>:B

by the way, a system like scala is powerful enough to avoid using 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 } 
+14
source share

Well, you messed up this version of java a bit. Note that you are creating an instance of Comparator <Comparable <Object β†’ and you assign its value using a wildcard - why? You will not assign anything else to this variable. Not to mention that your getInstance also defines wildcards, while it returns all 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); } } 
+2
source share

All Articles