使用v.不使用`self`类型

Kev*_*ith 5 scala

鉴于以下特征:

scala> trait Foo { self => 
     |   def f: String = self.getClass.getName
     | }
defined trait Foo

scala> trait Bar { 
     |  def f: String = this.getClass.getName
     | }
defined trait Bar
Run Code Online (Sandbox Code Playgroud)

然后创建扩展它们的类:

scala> class FooImpl extends Foo {} 
defined class FooImpl

scala> class BarImpl extends Bar {}
defined class BarImpl
Run Code Online (Sandbox Code Playgroud)

然后f在新实例上调用它们的方法:

scala> (new FooImpl).f
res1: String = FooImpl

scala> (new BarImpl).f
res4: String = BarImpl
Run Code Online (Sandbox Code Playgroud)

REPL显示它们打印出相同的值 - 类的名称.

也许这不是一个好例子.但是,什么是使用的差异self在上面Foo相比Bar,它使用this

Tra*_*own 5

在你的情况下,没有区别 - 你只是使用另一个名称this.当您需要消除不同thiss 之间的歧义时,自我类型很有用.例如:

abstract class Foo { self =>
  def bar: Int
  def qux = new Foo {
    def bar = self.bar
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我们在def bar = this.bar这里写,编译器会抱怨我们的定义bar只是递归地调用自己,因为this它将指向Foo我们定义的匿名子类qux,而不是外部Foo.