Taken from Scala, how would you declare static data inside a function? . Do not use a method, but a function object:
val init = { // or lazy val var inited = false (config: Config) => { if (inited) throw new IllegalStateException inited = true } }
During the initialization of the outer region (in the case of val ) or the first access ( lazy val ), the body of the variable is executed. Thus, inited set to false . The last expression is an anonymous function, which is then assigned to init . Then, each subsequent access to init performs this anonymous function.
Note that it does not behave exactly like a method. That is, it is quite fair to call it without arguments. Then it will behave like a method with a final underscore method _ , which means that it will simply return an anonymous function without complaints.
If for some reason you really need the behavior of the method, you can make it private val _init = ... and call it from the public def init(config: Config) = _init(config) .
source share