This is a follow-up question to my previous initialization variable question.
Suppose we're dealing with this context:
object AppProperties {
private var mgr: FileManager = _
def init(config: Config) = {
mgr = makeFileManager(config)
}
}
The problem with this code is that any other method in AppProperties
might reassign mgr
. Is there a technique to better encapsulate mgr
so that it feels like a val
for the other methods? I've thought about something like this (inspired by 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))
}
}
... but this feels rather heavyweight to me (and initialization reminds me too much of C++ :-)). Any other idea?