【发布时间】:2018-06-07 03:22:52
【问题描述】:
Scala 中的特征类似于 Java 中的接口或抽象类。因此,不可能直接从特征中获取实例。但是,我找到了一种实例化特征的方法。这是我的工作:
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
以及以下内容:
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 上运行。在他们所有人中,只有特质!根本没有课。
特质如何以这种方式发挥作用?
【问题讨论】:
-
实际上比这简单得多。
new B {}
标签: scala