scala - 使用具有相同文件名和声明的特征
问题描述
我有抽象类 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 中的值税 ...
如何使用具有相同名称的字段的两个特征?
解决方案
理想的方法是为 tax 创建一个单独的 Trait,并从这个 Base traitTax
扩展Employee
and 。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
推荐阅读
- docker - Docker Image 在一台机器上正常运行,但在另一台机器上失败
- linux-device-driver - 如何在驱动程序的 probe() 函数中测试平台 i2c 设备的实际存在
- c++ - 宏参数的扩展如何在c ++中工作
- asp.net-mvc - 使用 Service Worker - 在线时使用获取的数据的 MVC 视图
- php - 为什么在我的 html 文件中找不到 svg 代码行
- r - 为什么 R 找不到函数“getStates”
- matlab - 如何通过 fsolve 函数获得这些具有灵活参数的方程的根?
- java - 我可以强制在 Spring 中包含两个标题中的至少一个吗?
- couchbase - 如何在 Couchbase 中获取今天插入的文档?
- javascript - 展平数组的最有效方法
| T> 在 JavaScript 中