scala - 特质中的惰性断言

标签 scala

我发现我偶尔想在一个特征中写一个任意的断言,或者在我想要断言的东西还没有完全定义的其他地方。

trait Foo {
  val aList: List[String]
  val anotherList: List[String]

  def printPairs = aList.zip(anotherList).foreach(println)

  assert(aList.size == anotherList.size) // NullPointerException, because these references are undefined right now.
}

我想我正在寻找的概括是一个在类完全定义和实例化后(总是)触发的钩子(Hook),因为这是我通常放在构造函数中的那种检查。

最佳答案

您可以使用早期定义来实现(在 Scala Language Reference 中搜索以获取更多信息) - 使用与您编写的完全一样的特征,您可以将其扩展如下:

class Bar(l1: List[String], l2: List[String]) extends {
  val aList = l1
  val anotherList = l2
} with Foo

这将在调用 assert 之前启动列表, 所以:
new Bar(List("a", "b"), List("c", "d")) // built successfully
new Bar(List("a", "b"), List("c", "d", "e")) // throws exception

当然 - 这不完全是你所要求的(一个总是在构造后调用的“钩子(Hook)”),因为任何扩展类都必须知道哪些成员必须“尽早”覆盖,但据我所知,这是你能做到的最接近的得到。

关于scala - 特质中的惰性断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40687773/

相关文章:

Scala:将执行上下文传递给 Future 的 map 函数的语法

scala - 将 scala 数据框中的逗号分隔值拆分为多行

java - scalac如何标记编译文件?

scala - PairRDD 的总和值

Scala:抽象类构造函数参数与 Trait val 成员?

scala - 如何在 Scala 中覆盖 `org.elasticsearch.client.FilterClient#doExecute()`?

Scala - 遍历案例类名称以用作类型参数

scala - 如何调用仅存在于任一类型中的两种类型之一的方法?

scala - 基于条件构建不可变列表

scala - 如何在scala中保存RandomForestClassifier Spark模型?