What are the pros of using traits over abstract classes?

前端 未结 7 1466
-上瘾入骨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:28

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

提交回复
热议问题