Scala's own argument

This example is from one of 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 argument itself allows us to refer to this object as to ourselves, and not to it.

What would this expression mean?

+4
source share
1 answer

self- this is just an alias thisin the object in which it is declared, and can be any valid identifier (but not this, otherwise an alias is not created). Therefore, selfit can be used to refer thisto an external object from within the internal object, where thisotherwise it means something else. Perhaps this example will clarify the situation:

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` 
+7
source

All Articles