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

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

    Section 2.3 "Selftype Annotations" of Martin Odersky's original Scala paper Scalable Component Abstractions actually explains the purpose of selftype beyond mixin composition very well: provide an alternative way of associating a class with an abstract type.

    The example given in the paper was like the following, and it doesn't seem to have an elegant subclass correspondent:

    abstract class Graph {
      type Node <: BaseNode;
      class BaseNode {
        self: Node =>
        def connectWith(n: Node): Edge =
          new Edge(self, n);
      }
      class Edge(from: Node, to: Node) {
        def source() = from;
        def target() = to;
      }
    }
    
    class LabeledGraph extends Graph {
      class Node(label: String) extends BaseNode {
        def getLabel: String = label;
        def self: Node = this;
      }
    }
    

提交回复
热议问题