Scala self 类型特征实例化

标签 scala

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 如何以这种方式工作?

最佳答案

这个实例化类似于 JavaAnonymous 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 , 自 DummyUserUser 的子类型.

还有一个 cake patternScala 中了解如何使用 self type 来实现 Dependency Injection

关于Scala self 类型特征实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50732472/

相关文章:

postgresql - Scala 的任何中途体面的 jdbc 包装器?

scala - 使用 scala 检索与给定节点相关的 neo4j 节点

scala - 为什么DataFrame.collect()不返回数组

scala - 验证错误: Uninitialized object exists on backward branch/JVM Spec 4. 10.2.4

mongodb - 如何将 JSON 日期转换为 BSONDateTime?

scala - 如何使用 scala 删除重复的元组?笛卡尔 Scala Spark

android - 在 sbt android 项目中使用我的 java 项目 jar

java - 从字符串中提取版本号的正则表达式模式

scala - 找不到类型 scalaz.Applicative 的证据参数的隐式值

java - 反向路由 玩 POST payload