【问题标题】:Scala intermediate early initializerScala 中间早期初始化器
【发布时间】:2020-01-17 13:12:02
【问题描述】:

在 Scala 中有没有办法使用中间早期初始化器?

这是我要编译的内容:

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


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

编辑:回答 Luis 的问题

使用 scalatest,可以使用 trait 构造函数来组织固定装置。我想对一个子夹具进行参数化,并使用超级夹具中的一个字段进行早期初始化。

这是另一个与实际最大规模案例相关的例子:

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

【问题讨论】:

  • 根据 Scala 语法 EarlyDefs 必须在任何其他父类或特征之前。 - scala-lang.org/files/archive/spec/2.13/…
  • 你能告诉我们你为什么想要这个吗?也许有更好的方法来实现这一点。

标签: scala traits scalatest fixtures


【解决方案1】:

只需用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

【讨论】:

  • 它打印 0 因为它是 Int 的未初始化值,请尝试使用另一个整数。
  • @montrivo 你“尝试另一个整数”:)
  • 我的错,我在尝试您的示例时删除了惰性修饰符。太懒了.. :) 谢谢!
  • 这是一个关于该主题的 scala 论坛主题:scala-lang.org/old/node/6077
【解决方案2】:

可能有替代方法来编写测试,而不必使用早期初始化程序(已弃用),例如以下可能会提供一些想法

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

【讨论】:

  • 该示例无法解决初始化期间SpecialCaseFixture.specialCaseValue 不可用的问题。如果您在SpecialCaseFixture 的正文中添加println 语句,它将打印null
猜你喜欢
  • 2011-06-10
  • 2021-07-19
  • 1970-01-01
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
  • 2015-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多