scala 中的 Trait 类似于 Java 中的接口(interface)或抽象类。因此,不可能直接从特征中获取实例。但是,我找到了一种实例化特征的方法。这是我所做的:
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。在所有这些中,只有特征!根本没有课。
trait 如何以这种方式工作?
最佳答案
这个实例化类似于 Java 的 Anonymous Classes实例化,所以当new Tweeter with User
它实际上是为 Tweeter with User
创建一个新的匿名实例 匿名类。
和new Tweeter with User
对于这个不编译,因为它失去了 name
的实现方法。实际上你需要像这样实现它:
val t = new Tweeter with User {
override def name: String = "hello world"
}
new Tweeter with User with DummyUser
您只需要将其声明为 new Tweeter with DummyUser
, 自 DummyUser
是 User
的子类型.
还有一个 cake pattern在 Scala 中了解如何使用 self type 来实现 Dependency Injection。
关于Scala self 类型特征实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50732472/