例如假设我有
interface ICar {...}
class Car implements ICar {...}
在Scala我想做
new MyScalaClass with ICar
但是使用ICar的java实现即Car。这样做的语法是什么?
答案 0 :(得分:4)
您可以使用对象聚合,但将聚合封装在特征中。假设您有以下Java代码:
interface ICar {
public void brake();
}
public class Car implements ICar {
public void brake() { System.out.println("BRAKE !!!"); }
}
然后您可以定义以下Scala特征:
trait HasCar { self: ICar =>
private val car = new Car
def brake() = car.brake()
}
最后,您可以将所需的一切混合到课堂中:
val c = new MyScalaClass extends ICar with HasCar
c.brake // prints "BRAKE !!!"
答案 1 :(得分:2)
new MyScalaClass with ICar
是执行此操作的语法,但如果ICar
中的方法未在MyScalaClass
中实现,则MyScalaClass with ICar
是一个抽象类并且可以'建造。因此,您需要为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") }
答案 2 :(得分:2)
您不能使用with
混合两个类。只允许一个类,加上任意数量的特征或接口。因此:
class MyScalaClass
class Car
new MyScalaClass with Car
// error: class Car needs to be a trait to be mixed in