Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala trait syntax

Tags:

scala

scalatra

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?

like image 536
randombits Avatar asked Jun 14 '13 00:06

randombits


People also ask

How do you declare a trait in Scala?

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.

How do you call a trait in Scala?

Use the extends keyword to extend a trait. Then implement any abstract members of the trait using the override keyword: Scala 2. Scala 3.

How do traits work in Scala?

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.

Can Scala traits have fields?

Traits can have methods(both abstract and non-abstract), and fields as its members.


1 Answers

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."

like image 67
Randall Schulz Avatar answered Sep 28 '22 19:09

Randall Schulz