scala 随笔(3)trait 和trait冲突解决

来源:互联网 发布:国庆假期游戏数据分析 编辑:程序博客网 时间:2024/06/11 08:07
trait 可以类似于抽象类,域和方法可以有定义,也可以抽象

trait 一般表示单一的功能,

当引用多个trait时,如果存在相同的值或者方法,需要人为解决冲突,

冲突问题
  1. trait A {
  2. var x =13;
  3. def f = x+12
  4. }
  5. trait B {
  6. def x =14;
  7. def f =x*12
  8. val c =123
  9. }
  10. class C extends A with B {
  11. }
  12. object EnumerationColor {
  13. def main(args: Array[String]): Unit = {
  14. println( new C().x)
  15. println( new C().f)
  16. }
  17. }

Error:(20, 7) class C inherits conflicting members:
  variable x in trait A of type Int  and
  method x in trait B of type => Int
(Note: this can be resolved by declaring an override in class C.);
 other members with override errors are: f
class C extends A with B {

解决冲突方法 。重写
  1. trait A {
  2. var x =13;
  3. def f = x+12
  4. val c = 23
  5. }
  6. trait B {
  7. def x =14;
  8. def f =x*12
  9. val c =123
  10. }
  11. class C extends A with B {
  12. override val x= super[A].x +super[B].x+ c
  13. override val f= super[B].f
  14. override val c: Int = 12
  15. }
  16. object EnumerationColor {
  17. def main(args: Array[String]): Unit = {
  18. println( new C().x)
  19. println( new C().f)
  20. }
  21. }
注意一下:super[A] 只能用于方法,不能用于域。也就是只能用def定义的才能用

原创粉丝点击