Make42 Make42 - 15 days ago 4x
Scala Question

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] =>


but I did not understand why it is better to use
instead of
here...!? Also, if I write
instead of
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
like an object in one of the methods of the trait later.


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()


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.