I've seen a couple of time code like this in Scala libraries. What does it mean?
trait SecuredSettings {
this: GlobalSettings =>
def someMethod = {}
...
}
I've seen a couple of time code like this in Scala libraries. What does it mean?
trait SecuredSettings {
this: GlobalSettings =>
def someMethod = {}
...
}
This trick is called "self type annotation".
This actually do two separate things at once:
this
reference (may be useful when you introduce nested class, because then you have several this
objects 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
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
.