2016-11-19 43 views
4

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

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

我想的是什么我要找的是(总是)后级大火被完全定义和实例化一个钩的推广,因为这是哪门子的检查,我一般会把在构造函数。

回答

1

可以使用早期的定义(搜索它在Scala Language Reference获取更多信息)做到这一点 - 与你的特质完全按照你写的,你可以按照如下进行扩展:

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

这将启动 - 这不正是你问(“钩子”是施工后总是调用),因为任何扩展的类必须知道哪些成员必须重写

new Bar(List("a", "b"), List("c", "d")) // built successfully 
new Bar(List("a", "b"), List("c", "d", "e")) // throws exception 

当然:调用assert,因此前清单“早”,但据我所知,这是你能得到的最接近的。

+0

我认为七分钟直到回答是我的记录。你说得对,这不是我想到的,但它非常接近。扩展类必须执行Early Definition子句,否则断言将失败,并且子句必须通过断言,否则断言将失败。无论哪种方式,只有断言存活的类才能被实例化。 – randomstatistic

+0

对于如何在Scala中实现这个问题,你可以经常看到2分钟的答案,有相当多的声望猎手,你可以让你松懈;)很高兴它有帮助! –

+3

'class Bar(val aList:List [String],val anotherList:List [String])扩展Foo'(一个稍微干净的版本) – jwvh