开发者

Scala class to implement two Java Interfaces - how?

开发者 https://www.devze.com 2023-01-03 18:14 出处:网络
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

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

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?

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.


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 {
  //...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号