Question

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);
    }

}
Was it helpful?

Solution 3

I've returned to the problem with more experience and solved it, although I think that is can 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
    }

}

OTHER TIPS

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top