[英]Scala class to implement two Java Interfaces - how?
I have just started learning Scala and I'm now wondering how I could implement two different Java interfaces with one Scala class? 我刚开始学习Scala,现在我想知道如何用一个Scala类实现两个不同的Java接口? Let's say I have the following interfaces written in Java
假设我有以下用Java编写的接口
public interface EventRecorder {
public void abstract record(Event event);
}
public interface TransactionCapable {
public void abstract commit();
}
But a Scala class can extend only one class at a time. 但是Scala类一次只能扩展一个类。 How can I have a Scala class that could fulfill both contracts?
我怎样才能拥有可以同时履行这两个合同的Scala类? Do I have to map those interfaces into traits?
我是否必须将这些界面映射到特征中?
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. 注意,我的Scala类将在Java中使用,因为我试图将用Scala编写的新功能注入到现有的Java应用程序中。 And the existing framework expects that both interface contracts are fulfilled.
现有框架期望两个接口合同都得到满足。
The second interface can be implemented with the with
keyword 第二个接口可以使用
with
关键字实现
class ImplementingClass extends EventRecorder with TransactionCapable {
def record(event: Event) {}
def commit() {}
}
Further on each subsequent interface is separated with the keyword with
. 进一步在每个后续接口上用关键字
with
分隔。
class Clazz extends InterfaceA
with InterfaceB
with InterfaceC {
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.