I am looking over the documentation for Scalatra and noticed an interesting snippet of code for syntax I haven't seen yet on : http://www.scalatra.org/2.2/guides/persistence/introduction.html
Specifically, it's this bit:
trait DatabaseSessionSupport { this: ScalatraBase =>
import DatabaseSessionSupport._
everything here makes sense except for the this: ScalatraBase =>
segment. What significance does it have here? Is it specific for the import below or for the entire trait?
In scala, trait is a collection of abstract and non-abstract methods. You can create trait that can have all abstract methods or some abstract and some non-abstract methods. A variable that is declared either by using val or var keyword in a trait get internally implemented in the class that implements the trait.
Use the extends keyword to extend a trait. Then implement any abstract members of the trait using the override keyword: Scala 2. Scala 3.
Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters. A trait definition looks just like a class definition except that it uses the keyword trait.
Traits can have methods(both abstract and non-abstract), and fields as its members.
That is called a "self-type annotation" and it requires that any use of trait DatabaseSessionSupport
in an instantiable class must be accompanied by ("mixed in with") a type consistent with ScalatraBase
. I have not looked at this specific code, but it is most likely a use of the so-called "Cake Pattern."
You can find many treatments of this concept both in Stack Overflow, in various blogs and in a classic paper by Odersky et. al. titled "Scalable Component Abstractions."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With