Trait
Scala中,trait和Java中的接口类似,不同的地方是,trait中可以包含实体方法。定义方式如下:
trait traitName {....} 比如:
scala> trait Talk {
| def hello(name:String) = println("Hello,"+name)
| }
defined trait Talk
Scala中,class可以添加trait;如果class没有父类,则用extends 添加trait,否则用with;class可以直接使用被添加的trait中的方法,示例如下:
scala> class People extends Talk
defined class People
scala> val peple = new People()
peple: People = People@1258b446
scala> peple.hello("Alice")
Hello,Alice
添加多个trait,示例如下:
scala> trait Talk {
| def hello(name:String) = println("Hello,"+name)
| }
defined trait Talk
scala> trait Run {
| def run() = println("I can run")
| }
defined trait Run
scala> class Animal
defined class Animal
scala> class People extends Animal with Run with Talk
defined class People
scala> val people = new People()
people: People = People@72215167
scala> people.run
I can run
scala> people.hello("Alice")
Hello,Alice
trait可以继承class,也可以添加其它trait,示例如下:
scala> class Bird
defined class Bird
scala> trait Sing extends Bird {
| def sing() = println("A bird can sing")
| }
defined trait Sing
scala> trait Walk
defined trait Walk
scala> trait SingAndWalk extends Sing with Walk
defined trait SingAndWalk
一旦一个trait继承了class,那么能添加该trait的只有该class或者其子类,示例如下:
scala> class Bird
defined class Bird
scala> trait BirdTrait extends Bird
defined trait BirdTrait
scala> class Parrot extends Bird
defined class Parrot
scala> class Deer
defined class Deer
scala> val bird = new Bird with BirdTrait
bird: Bird with BirdTrait = $anon$1@6c46215
scala> val parrot = new Parrot with BirdTrait
parrot: Parrot with BirdTrait = $anon$1@6f2e17a2
scala> val deer = new Deer with BirdTrait
:10: error: illegal inheritance; superclass Deer
is not a subclass of the superclass Bird
of the mixin trait BirdTrait
val deer = new Deer with BirdTrait
^
参考自:Programming Scala 2nd Edition
阅读(991) | 评论(0) | 转发(0) |