What are the pros of using traits over abstract classes?

前端 未结 7 1459
-上瘾入骨i
-上瘾入骨i 2021-01-30 10:12

Can someone please explain traits in Scala? What are the advantages of traits over extending an abstract class?

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 10:38

    The short answer is that you can use multiple traits -- they are "stackable". Also, traits cannot have constructor parameters.

    Here's how traits are stacked. Notice that the ordering of the traits are important. They will call each other from right to left.

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

提交回复
热议问题