请问有人能解释一下Scala中的特征(traits)吗?和继承抽象类相比,特征有什么优势?
简而言之,您可以使用多个traits——它们是“可堆叠”的。此外,traits不能具有构造函数参数。
下面是traits是如何叠加的。请注意,traits的顺序很重要。它们将从右到左相互调用。
class Ball {
def properties(): List[String] = List()
override def toString() = "It's a" +
properties.mkString(" ", ", ", " ") +
"ball"
}
trait Red extends Ball {
override def properties() = super.properties ::: List("red")
}
trait Shiny extends Ball {
override def properties() = super.properties ::: List("shiny")
}
object Balls {
def main(args: Array[String]) {
val myBall = new Ball with Shiny with Red
println(myBall) // It's a shiny, red ball
}
}
这个网站展示了一个良好的特征使用例子。Trait的一个重要优点是你可以继承多个Trait,但只能继承一个抽象类。Traits解决了许多多重继承的问题,同时允许代码重用。
如果您了解Ruby,Traits类似于Mix-ins。
package ground.learning.scala.traits
/**
* Created by Mohan on 31/08/2014.
*
* Stacks are layered one top of another, when moving from Left -> Right,
* Right most will be at the top layer, and receives method call.
*/
object TraitMain {
def main(args: Array[String]) {
val strangers: List[NoEmotion] = List(
new Stranger("Ray") with NoEmotion,
new Stranger("Ray") with Bad,
new Stranger("Ray") with Good,
new Stranger("Ray") with Good with Bad,
new Stranger("Ray") with Bad with Good)
println(strangers.map(_.hi + "\n"))
}
}
trait NoEmotion {
def value: String
def hi = "I am " + value
}
trait Good extends NoEmotion {
override def hi = "I am " + value + ", It is a beautiful day!"
}
trait Bad extends NoEmotion {
override def hi = "I am " + value + ", It is a bad day!"
}
case class Stranger(value: String) {
}
class Shuttle extends Spacecraft with ControlCabin with PulseEngine{
val maxPulse = 10
def increaseSpeed = speedUp
}
Traits对于将功能混入类中非常有用。请查看http://scalatest.org/。注意你可以将各种特定于领域的语言(DSL)混入测试类中。查看快速入门指南以了解Scalatest支持的一些DSL (http://scalatest.org/quick_start)