Search code examples
scalatraitsscalatestfixtures

Scala intermediate early initializer


Is there a way in scala to use an intermediate early initializer?

Here is what I'm trying to compile:

trait A { val valueA: Int = 0 }
trait B { 
  val valueB: Int 
  println(valueB)
}


class C extends A with { val valueB = valueA } with B

EDIT: reponse to Luis' question

With scalatest, fixtures can be organized with trait constructors. I'd like to parameterize one subfixture and early initialize with a field from a superfixture.

Here is another example that relates better to a real scalatest case:

class Test extends FreeSpec {
  trait CommonFixture {
    val commonCaseValue: Int = 1
  }
  abstract trait SpecialCaseFixture {
    val specialCaseValue: Int
  }

  "special case test #1" in new CommonCaseFixture with { val specialCaseValue = commonCaseValue } with SpecialCaseFixture {
    // all fixtures fields are accessible here
  }
}

Solution

  • Just override it with a lazy val:

    trait A { val valueA: Int = 100500 }
    trait B {
      val valueB: Int
      println(valueB)
    }
    class C extends A with B { lazy val valueB = valueA } 
    new C 
    // prints 100500