Scala class cant override compare method from Java Interface which extends java.util.comparator

大兔子大兔子 提交于 2019-12-01 06:23:41

It may be impossible. If this is wrong, I would like to know.

EDIT: But you can do this instead:

// CompareImpl.java
abstract class CompareImpl implements MiscUtilities.Compare {
  public int compare(Object o, Object o1) {
    return doCompare(o, o1);
  }

  public abstract int doCompare(Object o, Object o1);
}

// MyCompare.scala
object MyCompare extends CompareImpl {
  def doCompare(a: AnyRef, b: AnyRef) = 0
}

So you still have to write some Java, but only one trivial class for each interface like MiscUtilities.Compare.

Producing a standalone example is the first step to solving these sort of problems.

 ~/code/scratch/raw: cat Compare.java 
interface Compare extends java.util.Comparator {
}
 ~/code/scratch/raw: cat MyCompare.scala 
object MyCompare extends Compare  {
  def compare(a: AnyRef, b: AnyRef) = 0
}
 ~/code/scratch/raw: scalac MyCompare.scala Compare.java 
MyCompare.scala:1: error: object creation impossible, since method compare in trait Comparator of type (x$1: T,x$2: T)Int is not defined
object MyCompare extends Compare  {
       ^

The temptation is to extend Comparator[AnyRef] directly from MyCompare, along with Compare:

object MyCompare extends java.util.Comparator[AnyRef] with Compare  {
  def compare(a: AnyRef, b: AnyRef) = 0
}

But this leads to:

error: illegal inheritance;
 self-type MyCompare.type does not conform to java.util.Comparator[AnyRef]'s selftype java.util.Comparator[AnyRef]

So I'm inclined to agree that this isn't possible, at least directly. Write the class in Java, delegating to Scala if need be.

Does it work if you put [AnyRef] after MiscUtilities.Compare? I.e.,

class Compare extends MiscUtilities.Compare[AnyRef] {   
  def compare(a1:AnyRef, a2:AnyRef) = 0       
}

I tried that with java.util.Comparator directly and the compiler seemed happy.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!