Scala Traits 中的冲突字段 [英] Conflicting fields in Scala Traits

查看:41
本文介绍了Scala Traits 中的冲突字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解 Scala 如何通过考虑提到的特征的顺序来解决钻石继承情况.我很想知道它如何解决字段的相同问题.这是我想要理解的 -

I understand how scala addresses the diamond inheritance situation by considering the order of the traits mentioned. I am curious to understand how it solves the same issue for fields. Here is what I am trying to understand -

class A {print("A")}
trait B extends A {print("B") ; val x="b"}
trait C extends B {print("C")}
trait D extends A {print("D");  val x="d"}

object TraitsEx extends App {
  var d = new A with B with D
  println(d.x)
}

以上代码无法编译.

推荐答案

正如您所见,这并不神奇.如果这是 A 类的一个属性,那么您可以覆盖它 - 通过类线性化,您已经知道,每个 with X,其中 X extends A 将覆盖值:

Well not magically as you can see. If this was a property of A class, then you could override it - with class linearization, you already know, each with X, where X extends A would override values:

trait A {
  val x = "a"
}

trait B extends A {
  override val x = "b"
}

trait C extends A {
  override val x = "c"
}

object Main {
  def main(args: Array[String]): Unit = {
    println((new A {}).x)
    println((new A with B).x)
    println((new A with B with C).x)
  }
}

印刷品

a
b
c

然而,当每个类引入自己的 x 编译器无法证明覆盖其他 x 时,那么它就会让你解决这个问题.它还建议了一种解决方案:

However, when each class introduces its own x that compiler cannot prove to override other xs, then it will leave solving that problem to you. It also suggest one solution:

object TraitsEx extends App {
  var d = new A with B with D { override val x = "d" }
  println(d.x)
}

通过这种方式,您将覆盖所有不同的 x 并消除歧义.

this way you would override all different xs and remove ambiguity.

这篇关于Scala Traits 中的冲突字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆