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

后端 未结 3 401
遥遥无期
遥遥无期 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:26

    It is a self type annotation.

    This means that class Child must be of type C, i.e., creates inheritance dependencies which must satisfied for a given class.

    A small example:

    scala> trait Baz
    defined trait Baz
    
    
    scala> class Foo {
         | self:Baz => 
         | }
    defined class Foo
    
    
    scala> val a = new Foo
    :9: error: class Foo cannot be instantiated because it does not conform to its self-type Foo with Baz
           val a = new Foo
                   ^
    
    scala> val a = new Foo with Baz
    a: Foo with Baz = $anon$1@199de181
    
    
    scala> class Bar extends Foo with Baz
    defined class Bar
    

    In this case Foo is required to also be a Baz. Satisfying that requirement, a Foo instance can be created. Also, defining a new class (in this case Bar) there is also the requirement of it being Baz as well.

    See: http://www.scala-lang.org/node/124

提交回复
热议问题