Search code examples
scalatraitsself-reference

Why self instead of this in self reference?


I understand what the result of a self type is as in

trait SpellChecker {
  self: RandomAccessSeq[char] =>
  ...
}

from http://www.markthomas.info/blog/92

but I did not understand why it is better to use self instead of this here...!? Also, if I write asfd instead of self I also don't get a compiler error... so I am not quite sure "self" is all about. I don't see that it is possible to use self like an object in one of the methods of the trait later.


Solution

  • self is an alias for your SpellChecker instance. This is useful if you have nested structures (like classes). Consider this:

    trait Foo {
      self =>
    
      override def toString : String = "Foo here"
    
      class Bar {
        def print() : Unit = {
          println(s"this = $this")
          println(s"self = $self")
        }
        override def toString : String = "Bar here"
      }
    }
    
    val foo = new Foo {}
    val bar = new foo.Bar()
    bar.print()
    

    Outputs:

    this = Bar here 
    self = Foo here
    

    So if you want to reference the outer element you can use your alias. Using this means no alias, so this : Example => means "I dont need an alias for this, I just want to make sure this is mixed with Example". And you can name your alias however you like asfd is as fine as iLikeFries. self is just somewhat convention.