题
有人可以解释性状Scala呢?什么性状的优点延伸过一个抽象类?
解决方案
在简短的回答是,你可以使用多个特征 - 他们是“堆叠”。此外,性状不能有构造函数的参数。
下面的性状如何堆叠。请注意,特征的顺序是非常重要的。他们会打电话给对方从右到左。
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
}
}
其他提示
此网站给出性状使用的一个很好的例子。性状的一个大好处是,你可以扩展多个性状,但只有一个抽象类。性状解决许多与多重继承的问题,但允许代码重用。
如果你知道红宝石,特征类似于混合插件
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) {
}
Output : List(I am Ray , I am Ray, It is a bad day! , I am Ray, It is a beautiful day! , I am Ray, It is a bad day! , I am Ray, It is a beautiful day! )
这是我见过的最好的例子
Scala的在实践中:撰写性状 - 乐高样式: HTTP://gleichmann.wordpress。 COM / 2009/10/21 /阶式实践-构成-性状-LEGO风格/
class Shuttle extends Spacecraft with ControlCabin with PulseEngine{
val maxPulse = 10
def increaseSpeed = speedUp
}
的特征为用于混合功能合并到一类有用的。看看 http://scalatest.org/ 。注意:你怎么能在不同的领域特定语言(DSL)混合到一个测试类。看看快速入门指南看一些由Scalatest( http://scalatest.org/quick_start)
要在Java接口类似的,性状是用来通过指定的支持的方法的签名定义的对象类型。
与Java,Scala中允许性状被部分地实现;即,它可以定义默认实现的一些方法。
在对比类,性状可以不具有构造函数的参数。 性状是像类,但它们限定的那类可以提供具体的值和实现功能和字段的接口。
性状可以从其他性状或类继承。
我从书上的在Scala中,第一版编程的网站并更具体被叫节“的要性状,或不特质?”从第12章。
当你执行行为的可重复使用的集合,你将不得不决定是否要使用一个特质或抽象类。没有严格的规定,但是本节包含了一些准则,以考虑。
如果该行为不会被重用,然后使它的具体类。它不是毕竟可重复使用的行为。
如果它可能在多个不相关的类可以重复使用,使其成为一个性状。只有性状可以混合到的类层次结构的不同部分。
是在关于特质上面的链接更多的信息,我建议你阅读完整的部分。我希望这有助于。