Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? 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.

like image 881
puudeli Avatar asked Jun 18 '10 09:06

puudeli


People also ask

Can a class implement two interfaces Java?

A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.

Can a class implement two interfaces having same method?

No, its an errorIf two interfaces contain a method with the same signature but different return types, then it is impossible to implement both the interface simultaneously.


1 Answers

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 {   //... } 
like image 187
michael.kebe Avatar answered Sep 30 '22 18:09

michael.kebe