Valerin
Valerin

Reputation: 475

Scala - how to force a specific order of Traits

While the order of traits metter during their mixing then how I can force their order in a specific way. For example I have this:

val t = new Wink with Dash with Right with Left

and I want to put conditions, like if Right NOT Left and let say Dash COMES FIRST THEN Right OR Left

Upvotes: 3

Views: 204

Answers (1)

Alexander Weber
Alexander Weber

Reputation: 799

One way to accomplish such restrictions on ways of mixing traits is following:

trait Dash[T <: Dash[T]]
trait Right extends Dash[Right]
trait Left extends Dash[Left]

val t = new Wink with Dash[Right]

This way, [T <: Dash[T]] forces us to provide either Right or Left trait right away. (Right or Left in your requirements)

On the other hand Due to extension extends Dash[Right], Right or Left trait can not be mixed in without use of Dash. (Dash comes first in your requirements)

It also sounds as if you are checking some condition in order to decide between Right or Left. This could be done like this:

val t = if (p) new Wink with Dash[Right] else new Wink with Dash[Left]

Upvotes: 3

Related Questions