使用特征优于抽象类的优点是什么?

Zac*_*ese 81 scala traits

有人可以解释Scala中的特征吗?特性优于扩展抽象类有什么优势?

And*_*zlo 80

简短的回答是你可以使用多种特征 - 它们是"可堆叠的".此外,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
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 缺少构造函数参数几乎是使用特征中的类型参数来弥补的. (4认同)

agi*_*all 19

网站提供了一个很好的特质使用示例.特征的一大优点是你可以扩展多个特征,但只能扩展一个抽象类.Traits解决了多重继承的许多问题,但允许代码重用.

如果你知道红宝石,那么特质就像混合一样


Moh*_*amy 5

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) {
}
Run Code Online (Sandbox Code Playgroud)
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!
)