scala 随笔(3)trait 和trait冲突解决
来源:互联网 发布:国庆假期游戏数据分析 编辑:程序博客网 时间:2024/06/11 08:07
trait 可以类似于抽象类,域和方法可以有定义,也可以抽象
trait 一般表示单一的功能,
当引用多个trait时,如果存在相同的值或者方法,需要人为解决冲突,
冲突问题
trait A {
var x =13;
def f = x+12
}
trait B {
def x =14;
def f =x*12
val c =123
}
class C extends A with B {
}
object EnumerationColor {
def main(args: Array[String]): Unit = {
println( new C().x)
println( new C().f)
}
}
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 {
解决冲突方法 。重写
trait A {
var x =13;
def f = x+12
val c = 23
}
trait B {
def x =14;
def f =x*12
val c =123
}
class C extends A with B {
override val x= super[A].x +super[B].x+ c
override val f= super[B].f
override val c: Int = 12
}
object EnumerationColor {
def main(args: Array[String]): Unit = {
println( new C().x)
println( new C().f)
}
}
注意一下:super[A] 只能用于方法,不能用于域。也就是只能用def定义的才能用
阅读全文
0 0
- scala 随笔(3)trait 和trait冲突解决
- Scala Trait(一)
- Scala Trait(二)
- Scala Trait(三)
- Scala Trait(四)
- scala学习笔记3(trait)
- Scala:trait
- Scala Trait
- Scala Trait
- Scala-trait
- Scala Trait 详解(实例)
- Trait
- trait
- Trait
- trait
- trait
- trait
- Scala 的Trait和类型转换
- PHP高级面试题
- python基础学习总结
- HDU 6047 Maximum Sequence
- Map集合中value()方法与keySet()、entrySet()区别
- 自用基础9-异常
- scala 随笔(3)trait 和trait冲突解决
- 在VMware10中安装CentOS 6.4详解
- Java面向对象2
- ASP.NET中 RadioButtonList(单选按钮组)的使用
- PAT-B] 1007. 素数对猜想 [数论]
- JavaScript学习之Math对象
- 37.数独求解
- 自制远程数据采集、实时路径追踪系统的实现过程
- Http请求的工具类