应用
延伸DelayedInit
作为App
延伸DelayedInit
和Main
延伸App
。在Main
构造函数代码执行的延迟初始化的一部分。在介绍init如何工作之前,让我们看看构造函数变量声明和方法变量声明之间的差异。
scala> class A {
| def a(): Unit = { println(b) }
| val b = 1
| }
defined class A
在上面的例子b
稍后将声明和功能a()
首先声明。因为它是Compiler类的构造函数接受它的。
scala> def x: Int = {
| def y: Int = z
| val z = 1
| y
| }
<console>:12: error: forward reference extends over definition of value z
def y: Int = z
^
在上述情况下编译器抱怨说,它的前向参考。延迟初始化
已被弃用
类和对象(但要注意,不能性状)继承DelayedInit标记性状将有如下的初始化代码重写:代码变得delayedInit(代码)。
初始化代码包括所有语句和在初始化期间执行的所有值定义。
实施例:
trait Helper extends DelayedInit {
def delayedInit(body: => Unit) = {
println("dummy text, printed before initialization of C")
body // evaluates the initialization code of C
}
}
class C extends Helper {
println("this is the initialization code of C")
}
object Test extends App {
val c = new C
}
应导致以下被打印:
dummy text, printed before initialization of C
this is the initialization code of C
阅读更多关于延迟的init从这里(http://www.scala-lang.org/api/current /scala/DelayedInit.html) – pamu