问题描述
我刚开始学习Scala,现在我想知道如何用一个Scala类实现两个不同的Java接口?假设我有以下用Java编写的接口
I have just started learning Scala and I'm now wondering how I could implement two different Java interfaces with one Scala class? Let's say I have the following interfaces written in Java
public interface EventRecorder {
public void abstract record(Event event);
}
public interface TransactionCapable {
public void abstract commit();
}
但是Scala类一次只能扩展一个类。我怎样才能拥有可以同时履行这两个合同的Scala类?我是否必须将这些界面映射到特征中?
But a Scala class can extend only one class at a time. How can I have a Scala class that could fulfill both contracts? Do I have to map those interfaces into traits?
注意,我的Scala类将用于Java,因为我试图将用Scala编写的新功能注入到现有的Java应用程序中。并且现有框架期望两个接口契约都得到满足。
Note, my Scala classes would be used from Java as I am trying to inject new functionality written in Scala into an existing Java application. And the existing framework expects that both interface contracts are fulfilled.
推荐答案
第二个接口可以用 with keyword
The second interface can be implemented with the with
keyword
class ImplementingClass extends EventRecorder with TransactionCapable {
def record(event: Event) {}
def commit() {}
}
进一步说明每个后续接口用关键字与
分隔。
Further on each subsequent interface is separated with the keyword with
.
class Clazz extends InterfaceA
with InterfaceB
with InterfaceC {
//...
}
这篇关于Scala类实现两个Java接口 - 如何实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!