Implementing Multilevel Java Interfaces in Scala

爷,独闯天下 提交于 2021-01-27 04:42:33

问题


I have following hierarchy in java for my interface

public interface Identifiable<T extends Comparable<T>> extends Serializable {
    public T getId();
}
public interface Function extends Identifiable {
    public String getId();
}
public abstract class Adapter implements Function {
    public abstract String getId();
}

When I try to implement Adapter in scala as follows

class MultiGetFunction extends Adapter {
  def getId() : String = this.getClass.getName
}

I am getting following error

Multiple markers at this line
    - overriding method getId in trait Identifiable of type ()T; method getId has incompatible 
     type
    - overrides Adapter.getId
    - implements Function.getId
    - implements Identifiable.getId

回答1:


In general, it is a pain working with raw types in java code from Scala.

Try the below:

public interface Function extends Identifiable<String> {
    public String getId();
}

The error is probably due to inability of compiler to determine the type T as no type is mentioned when declaring Function extends Identifiable. This is explained from error:

:17: error: overriding method getId in trait Identifiable of type ()T; method getId has incompatible type

Scala is made to be compatible with Java 1.5 and greater. For the previous versions, you need to hack around. If you cannot change Adapter, then you can create a Scala wrapper in Java:

public abstract class ScalaAdapter extends Adapter {

    @Override
    public String getId() {
        // TODO Auto-generated method stub
        return getScalaId();
    }

    public abstract String getScalaId();

}

And then use this in Scala:

scala>   class Multi extends ScalaAdapter {
     |      def getScalaId():String = "!2"
     |   }
defined class Multi


来源:https://stackoverflow.com/questions/21473614/implementing-multilevel-java-interfaces-in-scala

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