Reputation: 2201
I'm learning Scala and found this code in the book's source code but no actual explanation for it in the book. I removed details for the sake of simplicity.
trait RefModel {
type Instrument = String
type Account = String
}
trait ExecutionModel {this: RefModel =>
case class Execution(account: Account, instrument: Instrument)
}
I'm wondering what this this: RefModel =>
is and what this suppose to do.
Upvotes: 1
Views: 58
Reputation: 51271
It's referred to as a "self type" meaning that the self (this) has to be the specified type as well as being the type (class or trait) being defined.
Think of it as an instruction to the compiler: Don't allow this trait (ExecutionModel
) to be instantiated unless RefModel
is included in the mixin. It means that members of RefModel
are available to the ExecutionModel
definition code.
Upvotes: 1
Reputation: 14217
This means trait ExecutionModel
need to compose RefModel
when initiate ExecutionModel
class. and This term called self type, it means ExecutionModel
need a RefModel
for this class.
it's often used by cake pattern for Dependency injection. so you can use it like:
object Foo extends ExecutionModel with RefModel // when initiate **ExecutionMode** bind with **RefModel**
Document: Cake Pattern
Upvotes: 1