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?
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 !!!"
new MyScalaClass with ICar is the syntax for doing that, but if there are methods in ICar that aren't implemented in MyScalaClass, MyScalaClass with ICar is an abstract class and can't be constructed. Hence, you'll need to provide method bodies for the methods in ICar.
// ICar.java
interface ICar{
void drive();
}
//MyScalaClass.scala
class MyScalaClass{
def brake = ()
}
//UseIt.Scala
// error: object creation impossible, since method
// drive in trait ICar of type => Unit is not defined
val foo = new MyScalaClass with ICar
// this works
val foo = new MyScalaClass with ICar { def drive = println("Driving") }
newexpression.