Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Scala, how do I mixin java interfaces into Scala code

Tags:

scala

For example suppose I have

interface ICar {...}
class Car implements ICar {...}

In Scala I wish to do

new MyScalaClass with ICar

But use the java implementation of ICar i.e. Car. What is the syntax for doing this?

like image 348
deltanovember Avatar asked Sep 19 '26 11:09

deltanovember


1 Answers

You can use object aggregation, but encapsulating the aggregation in a trait. Suppose you have the following Java code:

interface ICar {
  public void brake();
}
public class Car implements ICar {
  public void brake() { System.out.println("BRAKE !!!"); }
}

Then you can define the following Scala trait:

trait HasCar { self: ICar =>
  private val car = new Car
  def brake() = car.brake()
}

And finally you can mix everything you need into your class:

 val c = new MyScalaClass extends ICar with HasCar
 c.brake // prints "BRAKE !!!"
like image 136
paradigmatic Avatar answered Sep 21 '26 03:09

paradigmatic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!