Scala, advanced generic extending

v6ak picture v6ak · Nov 26, 2010 · Viewed 20.9k times · Source

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

}

Answer

shellholic picture shellholic · Nov 26, 2010

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
}