Scala 中级早期初始化器
Scala intermediate early initializer
scala 中有没有办法使用中间早期初始化程序?
这是我要编译的内容:
trait A { val valueA: Int = 0 }
trait B {
val valueB: Int
println(valueB)
}
class C extends A with { val valueB = valueA } with B
编辑:对路易斯问题的回应
借助 scalatest,可以使用特征构造函数来组织固定装置。我想参数化一个子夹具并使用超夹具中的字段提前初始化。
这是另一个与真实的最严重案例更相关的示例:
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
}
}
可能有其他方法可以编写测试而不必使用早期初始化程序(已弃用),例如以下可能会提供一些想法
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)
}
}
只需用 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
scala 中有没有办法使用中间早期初始化程序?
这是我要编译的内容:
trait A { val valueA: Int = 0 }
trait B {
val valueB: Int
println(valueB)
}
class C extends A with { val valueB = valueA } with B
编辑:对路易斯问题的回应
借助 scalatest,可以使用特征构造函数来组织固定装置。我想参数化一个子夹具并使用超夹具中的字段提前初始化。
这是另一个与真实的最严重案例更相关的示例:
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
}
}
可能有其他方法可以编写测试而不必使用早期初始化程序(已弃用),例如以下可能会提供一些想法
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)
}
}
只需用 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