在 Scala 中,Trait 为重用代码的一个基本单位。一个 Traits 封装了方法和变量。和 Interface 相比,它的方法可以有实现。这一点和抽象类定义类似。但和类继承不同的是,Scala 中类继承为单一继承,也就是说子类只能有一个父类

当一个类可以和多个 Trait 混合,这些 Trait 定义的成员变量和方法也就变成了该类的成员变量和方法。由此可以看出, Trait 集合了 Interface 和 抽象类 的优点,同时又没有破坏单一继承的原则。

Trait 不支持构造参数, 即 trait NoPoint(x: Int, y: Int) 会报错

Trait 会使类更加灵活

定义 Trait

trait Philosophical { // 没有声明基类, 继承 AnyRef
	def philosophize() {
		println("I consume memeory, therefor I am!")
	}
}

Trait 和 类混合, 使用 extends 或者 with

class Frog extends Philosophical {
	override def toString="gree"
}

val frog = new Frog
frog.philosophize // 这里和继承很像
val phil: Philosophical = frog

使用with方式

class Animal
trait HasLegs

class Frog extends Animal with Philosophical with HasLegs {  // 同时混入多个 trait 的时候。生效顺序从右到左
  override def toString="green"
}

var frog: Frog = new Frog with Philosophical with HasLegs  // 也可以使用这种方式调用。