如果在方法签名冲突的情况下如何在Scala中选择哪种特性来选择实现?
假设以下Java接口:
interface Dog {
default void makeSound() {
System.out.println("Woof");
}
default void beHappy() {
System.out.println("Wag tail");
}
}
interface Cat {
default void makeSound() {
System.out.println("Meow");
}
default void beHappy() {
System.out.println("Purrr");
}
}
现在假设我想要一只咕噜咕噜的狗,没有重新实现任何东西:
public class PurringDog implements Dog, Cat {
@Override
public void makeSound() {
Dog.super.makeSound();
}
@Override
public void beHappy() {
Cat.super.beHappy();
}
public static void main(String[] args) {
PurringDog purringDog = new PurringDog();
purringDog.makeSound(); //prints Woof
purringDog.beHappy(); //prints Purrr
}
}
如何在Scala中实现这一目标?
答案 0 :(得分:1)
你可以使用super和限定符:
trait Dog {
def makeSound(): Unit = println("Woof")
def beHappy(): Unit = println("Wag tail")
}
trait Cat {
def makeSound(): Unit = println("Meow")
def beHappy(): Unit = println("Purrr")
}
class PurringDog extends Dog with Cat {
override def makeSound() = super[Dog].makeSound()
override def beHappy() = super[Cat].beHappy()
}
object Test extends App {
val purringDog = new PurringDog
purringDog.beHappy()
purringDog.makeSound()
}
请注意,您只能将限定符用于直接混合的特征(出现在extends
或with
之后的特征),以便在层次结构上进行爬行(例如,具有基本特征{{ 1}})不适用于限定符。