What is the syntax meaning of “`class declaration head` { val_name : Type => `class body` }”

后端 未结 3 399
遥遥无期
遥遥无期 2021-01-18 05:11

When reading some articles about Scala, I found some examples with a curious syntax, which I might understand incorrectly

class Child[C <: Child[C]]         


        
3条回答
  •  北海茫月
    2021-01-18 05:41

    One very useful application of self types is a less verbose implementation of the CRTP ( http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern ), e.g.

    abstract class Base[Sub] {
      self:Sub =>
      def add(s:Sub) : Sub
    }
    
    case class Vec3(x:Double,y:Double,z:Double) extends Base[Vec3] {
      def add(that:Vec3) = Vec3(this.x+that.x, this.y+that.y, this.z+that.z)
    }
    

    Attempts to "cheat" with the inheritance won't work:

    class Foo extends Base[Vec3] {
      add(v:Vec3) = v
    }
    
    //error: illegal inheritance;
    //self-type Foo does not conform to Base[Vec3]'s selftype Base[Vec3] with Vec3
    //      class Foo extends Base[Vec3] {
    

提交回复
热议问题