Reputation: 15385
This example is from one of the Scala books:
trait IO { self =>
def run: Unit
def ++(io: IO): IO = new IO {
def run = { self.run; io.run }
}
}
object IO {
def empty: IO = new IO { def run = () }
}
The explanation given in the book is as follows:
The self argument lets us refer to this object as self instead of this.
What would that statement mean?
Upvotes: 5
Views: 189
Reputation: 55569
self
is just an alias to this
in the object in which it is declared, and it can be any valid identifier (but not this
, otherwise no alias is made). So self
can be used to reference this
from an outer object from within an inner object, where this
would otherwise mean something different. Perhaps this example will clear things up:
trait Outer { self =>
val a = 1
def thisA = this.a // this refers to an instance of Outer
def selfA = self.a // self is just an alias for this (instance of Outer)
object Inner {
val a = 2
def thisA = this.a // this refers to an instance of Inner (this object)
def selfA = self.a // self is still an alias for this (instance of Outer)
}
}
object Outer extends Outer
Outer.a // 1
Outer.thisA // 1
Outer.selfA // 1
Outer.Inner.a // 2
Outer.Inner.thisA // 2
Outer.Inner.selfA // 1 *** From `Outer`
Upvotes: 8