32

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.

1 Answer 1

54

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 {
  //...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I actually tried it but IntelliJ spewed out some vague syntax error. I have to try it again and see if the project was setup incorrectly.
Should it be mentioned, that subsequent interfaces are separated with the keyword with? Eg. x extends y with z with q.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.