本文介绍了“类声明头" { val_name : Type => 的语法含义是什么?`类体` }`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读一些关于Scala的文章时,我发现了一些语法奇怪的例子,我可能理解错误

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

class Child[C <: Child[C]] {
  some_name : C =>                   // here, what does it mean?
   var roomie : Option[C] = None

   def roomWith(aChild : C)= {
     roomie = Some(aChild)
     aChild.roomie = Some(this)
   }
}
class Boy extends Child[Boy]

我发现了具有特征的类似例子.

I found similar examples with traits.

这是否意味着我将 this 对象在类范围内声明为 C 的类型?

Does it mean that I declare this object in a class scope to by type of C ?

推荐答案

是自类型注解.

这意味着类 Child 必须是 C 类型,即创建必须满足给定类的继承依赖项.

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

一个小例子:

scala> trait Baz
defined trait Baz


scala> class Foo {
     | self:Baz =>
     | }
defined class Foo


scala> val a = new Foo
<console>: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

在这种情况下,Foo 也必须是 Baz.满足该要求,可以创建 Foo 实例.此外,定义一个新类(在本例中为 Bar)还要求它是 Baz.

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.

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

这篇关于“类声明头" { val_name : Type => 的语法含义是什么?`类体` }`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 14:22