代码之家  ›  专栏  ›  技术社区  ›  huynhjl bhericher

self:T=>和this:T=>在定义特征时有相同的含义吗?

  •  11
  • huynhjl bhericher  · 技术社区  · 15 年前

    看来我能用 self this

    scala> trait A { self: List[_] => }
    defined trait A
    
    scala> trait B { this: List[_] => }
    defined trait B
    

    这只是一个惯例,还是使用了不同于

    2 回复  |  直到 15 年前
        1
  •  18
  •   Miles Sabin    15 年前

    如果有引用封闭实例的成员类型,则使用“this”以外的名称可能很有用。例如

    trait Outer { self =>
      trait Inner {
        def outer = self
      }
    }
    

    比,,

    trait Outer {
      trait Inner {
        def outer = Outer.this
      }
    }
    

    在某些情况下。

        2
  •  6
  •   Mitch Blevins    15 年前

    它可以是任何东西:self、this、meep、blah等等。它仅由编译器用于确定要转换到哪个类(在对其调用方法时),并且实际上不会显示在字节码中。

    命名时要小心,因为本地标识符会覆盖自类型定义:

    trait A {
      def baz = println("baz!")
    }
    trait B {
      foo: A => 
      val foo = "hello"   
      // def bar = foo.baz // does not compile because foo is String, not A
      def bar = foo.substring(1)
    }