By Alvin Alexander. Last updated: October 10, 2020
This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a very short recipe, Recipe 8.9, “How to extend a Java interface like a Scala trait.”
Problem
You want to implement a Java interface in a Scala application.
Solution
In your Scala application, use the extends
and with
keywords to implement your Java interfaces, just as though they were Scala traits.
Given these three Java interfaces:
// java public interface Animal { public void speak(); } public interface Wagging { public void wag(); } public interface Running { public void run(); }
you can create a Dog
class in Scala with the usual extends
and with
keywords, just as though you were using traits:
// scala class Dog extends Animal with Wagging with Running { def speak { println("Woof") } def wag { println("Tail is wagging!") } def run { println("I'm running!") } }
The difference is that Java interfaces don’t implement behavior, so if you’re defining a class that extends a Java interface, you’ll need to implement the methods, or declare the class abstract
.
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |