0

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.

Make42
  • 12,236
  • 24
  • 79
  • 155

2 Answers2

3

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.

alextsc
  • 1,368
  • 1
  • 8
  • 13
  • So, I am actually mixing two things: The self reference alias of "self" and the inheritance prescription? In your example you did not give any inheritance prescription, did you? You just aliased `this`, right? – Make42 Oct 10 '16 at 08:56
  • Correct. It's not so much you mixing things but these are the two things you can do with a self-type annotation: 1) Create an alias for `this` and 2) Make sure the trait is only used in combination with some required type(s). You can do one, the other or both. Your question was just primarily phrased about the alias part. – alextsc Oct 10 '16 at 10:49
1

In this particular case, it makes no sense to rename this. It makes more sense in case of nesting, when you rename an outer this and access it in a nested template / object.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653