5

I'm currently working on a port of a jEdit plugin to write all code in Scala. However Im forced at a certain point to implement my own Comparator.

My simplified code is as follows:

class compare extends MiscUtilities.Compare {
  def compare(obj1: AnyRef, obj2: AnyRef): Int = 1
}

The MiscUtilities.Compare has the following signature when looking from IntelliJ

public static interface Compare extends java.util.Comparator {        
    int compare(java.lang.Object o, java.lang.Object o1);
}

However when im trying to compile my class I get a error saying:

error: class compare needs to be abstract, since method compare in trait Comparator of type (x$1: T,x$2: T)Int is not defined class compare extends MiscUtilities.Compare {

I have also tried with Any and java.lang.Object as types, but no luck so far.

Help is very much appreciated:)

Regards Stefan

4

3 回答 3

6

这可能是不可能的。如果这是错误的,我想知道。

编辑:但你可以这样做:

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

所以你仍然需要编写一些 Java,但每个接口只需要一个简单的类,比如MiscUtilities.Compare.

于 2010-07-25T13:14:47.373 回答
2

生成一个独立的例子是解决这类问题的第一步。

 ~/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  {
       ^

诱惑是Comparator[AnyRef]直接从扩展MyCompare,以及Compare

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

但这会导致:

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

所以我倾向于同意这是不可能的,至少直接是这样。用 Java 编写类,如果需要,委托给 Scala。

于 2010-07-25T13:24:44.327 回答
1

如果将 [AnyRef] 放在 MiscUtilities.Compare 之后,它会起作用吗?IE,

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

我直接使用 java.util.Comparator 进行了尝试,编译器似乎很高兴。

于 2010-07-25T14:34:20.760 回答