Scala 类来实现两个 Java 接口 - 如何?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3068540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:11:21  来源:igfitidea点击:

Scala class to implement two Java Interfaces - how?

javascalainterface

提问by puudeli

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

我刚刚开始学习 Scala,现在想知道如何用一个 Scala 类实现两个不同的 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. How can I have a Scala class that could fulfill both contracts? Do I have to map those interfaces into traits?

但是 Scala 类一次只能扩展一个类。我怎样才能拥有一个可以满足两个合同的 Scala 类?我是否必须将这些接口映射到特征中?

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.

请注意,我将在 Java 中使用我的 Scala 类,因为我试图将用 Scala 编写的新功能注入到现有的 Java 应用程序中。现有框架期望两个接口契约都得到满足。

采纳答案by michael.kebe

The second interface can be implemented with the withkeyword

第二个接口可以用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 {
  //...
}