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

后端 未结 11 2000
名媛妹妹
名媛妹妹 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:30

    Update: A principal difference is that self-types can depend on multiple classes (I admit that's a bit corner case). For example, you can have

    class Person {
      //...
      def name: String = "...";
    }
    
    class Expense {
      def cost: Int = 123;
    }
    
    trait Employee {
      this: Person with Expense =>
      // ...
    
      def roomNo: Int;
    
      def officeLabel: String = name + "/" + roomNo;
    }
    

    This allows to add the Employee mixin just to anything that is a subclass of Person and Expense. Of course, this is only meaningful if Expense extends Person or vice versa. The point is that using self-types Employee can be independent of the hierarchy of the classes it depends on. It doesn't care of what extends what - If you switch the hierarchy of Expense vs Person, you don't have to modify Employee.

提交回复
热议问题