Define a single trait out of multiple traits constrained by self-types

102 Views Asked by At

I have two abstract class that looks as follow:

abstract class BddAsyncSpec extends AsyncFeatureSpec
  with Matchers
  with GivenWhenThen
  with BeforeAndAfter
  with BeforeAndAfterAll

abstract class BddSpec extends FeatureSpec
  with Matchers
  with GivenWhenThen
  with BeforeAndAfter
  with BeforeAndAfterAll

as you can see, the mixin part looks the same. My question is, how to abstract the mixin part, that when I add more trait, then it applies for BddAsyncSpec and BddSpec.

2

There are 2 best solutions below

0
Mario Galic On BEST ANSWER

Try

trait MyTraits extends Matchers
  with GivenWhenThen with BeforeAndAfter with BeforeAndAfterAll { this: Suite with Informing => }

abstract class BddAsyncSpec extends AsyncFeatureSpec with MyTraits
abstract class BddSpec extends FeatureSpec with MyTraits

where we use self-type

this: Suite with Informing =>

because, for example, GivenWhenThen requires Informing

trait GivenWhenThen { this: Informing =>

and BeforeAndAfter and BeforeAndAfterAll require Suite

trait BeforeAndAfter extends SuiteMixin { this: Suite =>

Self-types are a way of specifying what the trait requires in order to be mixed-in.

0
Volty De Qua On

With another trait that is a set of common traits?

trait T1; trait T2
trait Common extends T1 with T2
abstract class BaseA; abstract class BaseB;
abstract class A extends BaseA with Common
abstract class B extends BaseB with Common