所以我似乎找到了答案。我决定采用 DelayedInit trait 方法——我只是执行延迟代码(并计算它被执行的次数),然后当我认为我已经看到足够的初始化时执行所需的代码(扩展中的每个类一个等级制度)。我把它包装成一个特征:
trait AfterInit extends DelayedInit {
def afterInit
private var initCount = 0
private def getInitNumber(clazz: Class[_]):Int =
if (clazz.getSuperclass == classOf[java.lang.Object]) 0 else getInitNumber(clazz.getSuperclass) + 1
final def delayedInit(x: => Unit) {
x
initCount += 1
if (getInitNumber(this.getClass) + 1 == initCount) afterInit
}
}
用法:
abstract class A(id:String) extends AfterInit {
var sum = 0
def add(n:Int) = { sum += n; sum }
def afterInit = if (sum > 10) () else throw new Exception
}
class B extends A("B") {
val add1 = add(50)
}
new B // no exception
class C extends A("C") {
val add2 = add(5)
}
new C // exception is thrown, since the `sum` was too small