什么是自我=>用于?

时间:2011-12-16 10:59:40

标签: scala

  

可能重复:
  What does “outer =>” really mean?

当我查看源代码:scala / src / library / scala / Option.scala

sealed abstract class Option[+A] extends Product with Serializable {
  self =>

我喜欢自己用的东西。我知道自我类型的正常用法是限制特征可以混合的类。例如:

scala> trait A
defined trait A

scala> trait NeedA {self: A =>}
defined trait NeedA

scala> new NeedA {}
<console>:10: error: illegal inheritance;
 self-type java.lang.Object with NeedA does not conform to NeedA's selftype NeedA with A
              new NeedA {}
                  ^

scala> new NeedA with A {}
res39: java.lang.Object with NeedA with A = $anon$1@4d04a0e8

scala>

但是“this =&gt;”事实并非如此。确实这个“这个=&gt;”用于?

1 个答案:

答案 0 :(得分:5)

它为此创建一个别名,这在内部类中可能很方便(对于OuterClass.this是同义的)

class A {self => 
   ...
  class B {
      // self is the enclosing A, synonymous for A.this
  }
}