Search code examples
scalascalatestself-type

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


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.


Solution

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