3

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?

3
  • @Kipton: What you just said is wrong, when you're talking about a new expression. Commented Aug 25, 2011 at 3:59
  • @Ken: You're right, I was thinking of defining a new class. Commented Aug 25, 2011 at 4:17
  • 2
    I must have missed something, what is the reason why you don't declare MyScalaClass as extending Car? Commented Aug 25, 2011 at 8:06

3 Answers 3

4

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

Comments

2

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") }

Comments

2

You can't mix two classes using with. Only one class is allowed, plus any number of traits or interfaces. Hence:

class MyScalaClass
class Car
new MyScalaClass with Car
// error: class Car needs to be a trait to be mixed in

Comments

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.