用 self 和 this references 理解真正的蛋糕模式代码

Understanding real cake pattern code with self and this references

最近学习了cake pattern以及self =>self:T =>的用法区别(见here). The difference between these technicalities and real Scala code as remarked here continue to create me problems. For instance, see the following code snippet taken from the Inox project:

trait Trees
  extends Expressions
     with Constructors
     with Extractors
     with Types
     with Definitions
     with Printers
     with TreeOps { self =>

     ...

     val interpolator: Interpolator { val trees: Trees.this.type } = new {
      protected val trees: Trees.this.type = Trees.this
     } with Interpolator    

     ...
}

综上所述,整个片段对我来说意义不大(而且它是代码中经常重复的模式),让我解释一下:

  1. 这是什么语法?

val interpolator: Interpolator { ... }

到现在我写了val name: Type = value,这里没有相等的。

  1. Trees.this.type应该是一个类型,但是什么类型呢?它应该在 Trees 特征中定义,我打赌 this 上下文与 trait Trees 上下文不同(与问题 1 相关)。我还查看了文件 Interpolators,但似乎没有类型元素。

  2. 最大的一行是protected val trees: Trees.this.type = Trees.this

谁能给我解释一下这是怎么回事?

  1. 这是一个类型为 Interpolator { val trees: Trees.this.type } 的变量 interpolator 的声明。类型 Interpolator { val trees: Trees.this.type }Interpolator 的子类型,但是 refined 有额外的限制,即 trees 不仅仅是一些 Trees,而是 [的一个具体实例=17=],即单例类型Trees.this.type。在类型 Interpolator { val trees: Trees.this.type }new { ... } with Interpolator.

    之间有一个等号-=-符号:

    单独演示语法的较短示例:

    trait Foo {
      val trees: Any
    }
    def interpolator: Foo { val trees: Int } = 
      new Foo { val trees = 42 }
    
    interpolator.trees + 58
    
  2. Trees.this.type 是值 thissingleton type。这种类型只有一个值:Trees.this.

    演示 .type 用法的较短示例:

    class Bar
    val b = new Bar
    val c: b.type = b
    
  3. 您正在将值 trees 设置为 Trees.this。您还向编译器保证 trees 不仅仅是一些 Trees,而且 trees 是单例类型 Trees.this.type 的单例值 Trees.this,它是Trees.

  4. 的严格子类型