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