2009-08-04 134 views

回答

79

简单的答案是,你可以使用多种特质 - 它们是“可堆叠的”。另外,特征不能有构造函数参数。

以下是特征的堆叠方式。请注意,这些特征的排序很重要。他们会从右到左互相打电话。

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 
    } 
} 
+3

构造函数参数的缺乏几乎是使用特征中的类型参数组成的。 – Jus12 2011-10-19 14:00:00

17

site给人性状使用的一个很好的例子。性状的一大优点是可以扩展多个特征,但只能扩展一个抽象类。性状解决了多重继承的许多问题,但允许重用代码。

如果你知道红宝石,特征类似于混合插件

3

特征对于将功能混合到类中很有用。看看http://scalatest.org/。请注意,您可以如何将各种领域特定语言(DSL)混合到一个测试类中。查看快速入门指南以查看Scalatest支持的一些DSL(http://scalatest.org/quick_start

1

与Java中的接口类似,通过指定受支持方法的签名来使用特征来定义对象类型。

与Java不同,Scala允许部分实现特征;即可以为某些方法定义默认实现。

与类相反,特征可能没有构造函数参数。 特征就像类,但它定义了一个函数和字段的接口,类可以提供具体的值和实现。

特征可以从其他特征或类继承。

4
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! 
) 

1

我从斯卡拉书编程网站报价,第一版,更具体的部分当你实现一个名为“To trait, or not to trait?”从第12章

可重复使用的行为集合,您将不得不决定是使用特征还是抽象类。没有确定的规则,但本部分包含一些要考虑的准则。

如果该行为不会被重用,那么将其作为具体的类。毕竟这不是可重用的行为。

如果它可能在多个不相关的类中重复使用,请将其作为特征。只有特征可以混合到类层次结构的不同部分。

上面的链接有关于性状的信息有点多,我建议你阅读完整章节。我希望这有帮助。

相关问题