sergeda
sergeda

Reputation: 2201

Can somebody explain this Scala code?

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

Answers (2)

jwvh
jwvh

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

chengpohi
chengpohi

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

Related Questions