这是my previous initialization variable question的后续问题。如何在Scala中模拟“分配一次”变量?
假设我们正在处理此背景下:
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++ :-))。任何其他想法?
有趣的方法。 – Debilski 2010-12-09 23:54:26
聪明,我喜欢它! – 2010-12-10 08:19:40
最后的解决办法张贴在这里:http://stackoverflow.com/questions/4404024/how-to-simulate-an-assign-once-var-in-scala/4407534#4407534 – 2010-12-10 09:55:21