0

I've seen a couple of time code like this in Scala libraries. What does it mean?

trait SecuredSettings {
  this: GlobalSettings =>

  def someMethod = {}
   ...
}
Anton
  • 4,395
  • 7
  • 32
  • 46
  • Ok, but in this trait what would be the purpose of this function declaration? I don't get it – Anton Oct 15 '14 at 01:47
  • In this case it is not an anonymous function. – Don Roby Oct 15 '14 at 01:51
  • 2
    It is a self type annotation. – Don Roby Oct 15 '14 at 02:00
  • possible duplicate of [What is the syntax meaning of "\`class declaration head\` { val\_name : Type => \`class body\` }"](http://stackoverflow.com/questions/8031596/what-is-the-syntax-meaning-of-class-declaration-head-val-name-type-cl) –  Oct 16 '14 at 21:01

2 Answers2

2

This trick is called "self type annotation".

This actually do two separate things at once:

  1. Introduces a local alias for this reference (may be useful when you introduce nested class, because then you have several this objects in scope).
  2. Enforces that given trait is mixable only into subtypes of some type (this way you assume you have some methods in scope).

Google for "scala self type annotation" for many discussion about this subject.

The scala-lang.org contains a pretty descent explanation of this feature: http://docs.scala-lang.org/tutorials/tour/explicitly-typed-self-references.html

There are numerous patterns which use this trick in non-obvious way. For a starter, look here: http://marcus-christie.blogspot.com/2014/03/scala-understanding-self-type.html

Luís Cruz
  • 14,780
  • 16
  • 68
  • 100
1
trait A {
  def foo
}

class B { self: A =>
  def bar = foo //compiles
}

val b = new B //fails
val b = new B with A //compiles

It means that any B instances must inherit (mix-in) A. B is not A, but its instances are promised to be so, therefore you can code B as if it were already A.

Ryoichiro Oka
  • 1,949
  • 2
  • 13
  • 20