1

When I look at the code of scala.collection.TraversableLike I see that it starts with self =>

What does it mean?

rapt
  • 11,810
  • 35
  • 103
  • 145

2 Answers2

4

This is usually used as an alias to "this" variable. Why do you even need this? Consider a simple example:

class A{
  self=>
  def generate = 5

  class B{
    def generate:Int = {
      self.generate+5
    }
  }
  def o = (new B).generate
}

val a = new A

a.o

If you change "self" to "this" you will get StackOverflowException. Why? Because "this.generate" inside the nested class refers to the method "generate" of class B. So in order to get access to the method "generate" of class A we created an alias to "this". You could have also wrote:

A.this.generate

instead. And it works too.

You might me also interested in this article. http://www.markthomas.info/blog/92

ig-melnyk
  • 2,769
  • 2
  • 25
  • 35
3

It's something called self-type annotation and allows two things:

  • aliasing this (helpful in nested classes or traits, where this would give you the access to the inner class, and self would give you the access to the outer class),
  • specifying additional requirements about this (it works very similar to inheritance then, you can see examples and differences here)
Community
  • 1
  • 1
Paweł Jurczenko
  • 4,431
  • 2
  • 20
  • 24
  • Thanks. Could you give an example of (2) - specifying additional requirements about `this`? – rapt Jun 22 '16 at 17:56
  • There are a few really good examples here: http://stackoverflow.com/questions/1990948/what-is-the-difference-between-self-types-and-trait-subclasses . If you'll have any further questions, feel free to ask ;) – Paweł Jurczenko Jun 22 '16 at 18:21