0

是否可以参数化一个或多个特征以进行混合?我下面的示例无法编译,但 IntelliJ 的智能感知确实提供了正确的类型。

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
4

1 回答 1

1

It is impossible to mix traits dynamically because the Scala compiler generates a new anonymous class per mixin to support this functionality on the 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

There are several similar questions to this one with detailed answers on why it's impossible dynamically and how it can be done (but really should not!) using macros.

Mixing in a trait dynamically

Dynamic mixin in Scala - is it possible?

How do I create an instance of a trait in a generic method in scala?

于 2013-11-04T12:50:26.300 回答