Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 237
v6ak Avatar asked Nov 26 '10 13:11

v6ak


2 Answers

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
}
like image 142
shellholic Avatar answered Dec 04 '22 11:12

shellholic


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);
    }
}
like image 44
Mirek Pluta Avatar answered Dec 04 '22 09:12

Mirek Pluta