在Scala中Trait类似于Java中的接口或抽象类。因此,无法直接从Trait中获取实例。但是我发现了一种实例化Trait的方法。下面是我所做的:
trait B {
def bId = 1
}
trait A { self: B =>
def aId = 2
}
val a = new A with B // The type of a is "A with B", a's value is $anon$1@6ad16c5d
and the following:
trait User {
def name: String
}
trait DummyUser extends User {
override def name: String = "foo"
}
trait Tweeter { self: User =>
def tweet(msg: String) = println(s"$name: $msg")
}
val t = new Tweeter with User // This doesn't compile
val t = new Tweeter with User with DummyUser // This does work!
// t: Tweeter with User with DummyUser = $anon$1@72976b4
t.tweet("hello") // result is: "foo: hello"
这两段代码都适用于Scala 2.12版本。它们全部只使用了trait,没有任何class。
trait如何以这种方式工作呢?
new B {}
- jwvh