首页 > 解决方案 > 使用具有相同文件名和声明的特征

问题描述

我有抽象类 Person 和两个特征 Employee 和 Student

abstract class Person(val name: String) {
  val tax: Double
}

trait Employee {
  val salary: Double;
  lazy val tax: Double = salary * 0.1;
}

trait Student {
  val tax: Double = 0.0;
}

我需要使用这两个特征创建 2 个实例

studentEmployee = new Person("John") with Student with Employee {override var salary: Double = 1000};
employeeStudent = new Person("Mike") with Employee with Student {override var salary: Double = 1000};

我得到错误:

...继承相互冲突的成员:特征 Double 类型的 Employee 中的惰性值税和 Double 类型的特征 Student 中的值税 ...

如何使用具有相同名称的字段的两个特征?

标签: scalatraits

解决方案


理想的方法是为 tax 创建一个单独的 Trait,并从这个 Base traitTax扩展Employeeand 。Student理想情况下,特征应该像一个接口一样,不应该有实际的实现。实现应该是扩展此特征的类的一部分。

下面的实现解决了这个问题

abstract class Person(val name: String) {
}

trait Tax {
    val tax: Double

}
trait Employee extends Tax {
  val salary : Double;
  override val tax : Double ;
}

trait Student extends Tax {
  override val tax : Double;
}

var studentEmployee = new Person("John") with Student with Employee {
                   override val salary: Double = 1000;
                   override val tax = salary * 0.1};


var employeeStudent = new Person("Mike") with Employee with Student {
                  override val salary: Double = 1000 ;
                  override val tax = 0.0};

scala> studentEmployee.tax
res42: Double = 100.0

scala> employeeStudent.tax
res43: Double = 0.0


推荐阅读