montrivo
montrivo

Reputation: 175

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
  }
}

Upvotes: 2

Views: 150

Answers (2)

Dima
Dima

Reputation: 40510

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

Upvotes: 4

Mario Galic
Mario Galic

Reputation: 48420

There are likely alternative ways to write the tests without having to use early initialisers (which are deprecated), for example the following might give some ideas

class FixturesSpec extends FlatSpec with Matchers {
  case class FixtureA(x: Int = 42)
  case class FixtureB(y: Int = -11)

  trait CommonFixture {
    val commonCaseValue: Int = 1
  }
  trait SpecialCaseFixture {
    val specialCaseValue: Int
  }

  "traits" should "be fixtures" in new SpecialCaseFixture with CommonFixture  {
    override val specialCaseValue = commonCaseValue
    specialCaseValue should be (1)
  }

  "case classes" should "be fixtures" in new FixtureA(FixtureB().y)  {
    x should be (-11)
  }
}

Upvotes: 1

Related Questions