在Scala中实现多级Java接口

在Scala中实现多级Java接口

本文介绍了在Scala中实现多级Java接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的接口

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

当我尝试按以下方式在 scala 中实现 Adapter

When I try to implement Adapter in scala as follows

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

我遇到以下错误

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

推荐答案

通常,使用Scala中的Java代码处理原始类型很麻烦.

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

请尝试以下操作:

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

该错误可能是由于编译器无法确定类型 T 所致,因为在声明 Function可扩展标识时未提及任何类型.这是从错误中解释的:

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:

Scala与Java 1.5及更高版本兼容.对于以前的版本,您需要四处寻找.如果您不能更改 Adapter ,则可以使用Java创建Scala包装器:

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

}

然后在Scala中使用它:

And then use this in Scala:

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

这篇关于在Scala中实现多级Java接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:06