What is the difference between self-types and trait subclasses?

后端 未结 11 1989
名媛妹妹
名媛妹妹 2020-11-22 08:53

A self-type for a trait A:

trait B
trait A { this: B => }

says that \"A cannot be mixed into a concrete cl

11条回答
  •  无人及你
    2020-11-22 09:31

    Another thing that has not been mentioned: because self-types aren't part of the hierarchy of the required class they can be excluded from pattern matching, especially when you are exhaustively matching against a sealed hierarchy. This is convenient when you want to model orthogonal behaviors such as:

    sealed trait Person
    trait Student extends Person
    trait Teacher extends Person
    trait Adult { this : Person => } // orthogonal to its condition
    
    val p : Person = new Student {}
    p match {
      case s : Student => println("a student")
      case t : Teacher => println("a teacher")
    } // that's it we're exhaustive
    

提交回复
热议问题