是否可以参数化一个或多个混合特征?我的下面的例子没有编译,但IntelliJ的intellisense确实提出了正确的类型。
class Student
class Students[A <: Student] {
def create = new Student with A
}
trait Major extends Student
trait Dormitory extends Student
trait Fraternity extends Student
val onCampus = new Students[Major with Dormitory]
val fratBoys = new Students[Major with Fraternity]
onCampus.create // is a: Student with Major with Dormitory
fratBoys.create // is a: Student with Major with Fraternity
答案 0 :(得分:1)
动态混合特征是不可能的,因为Scala编译器为每个mixin生成一个新的匿名类,以在JVM上支持此功能:
scala> trait A
defined trait A
scala> trait B
defined trait B
scala> new A with B
res0: A with B = $anon$1@40f8335a
这个问题有几个类似的问题,详细解答为什么动态不可能以及如何使用宏来完成(但实际上不应该!)。
Dynamic mixin in Scala - is it possible?
How do I create an instance of a trait in a generic method in scala?