Search code examples
genericsscalaextending

Scala, advanced generic extending


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

}

Solution

  • 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
        }
    
    }