这是对我的上一个初始化变量问题的跟进问题。
假设我们正在处理以下上下文:
object AppProperties {
private var mgr: FileManager = _
def init(config: Config) = {
mgr = makeFileManager(config)
}
}
这段代码的问题在于,
AppProperties
中的任何其他方法都可能重新分配 mgr
。是否有一种更好的封装技术,可以使 mgr
对其他方法感觉像一个 val
?我考虑过类似于这样的东西(受 this answer 的启发):object AppProperties {
private object mgr {
private var isSet = false
private var mgr: FileManager = _
def apply() = if (!isSet) throw new IllegalStateException else mgr
def apply(m: FileManager) {
if (isSet) throw new IllegalStateException
else { isSet = true; mgr = m }
}
}
def init(config: Config) = {
mgr(makeFileManager(config))
}
}
...但是这对我来说感觉有些笨重(而且初始化让我太想起C++了:-))。还有其他的想法吗?