title: How to simulate an “assign-once” var in Scala?
body: <p>This is a follow-up question to <a href="https://stackoverflow.com/questions/4400926/can-i-define-method-private-fields-in-scala">my previous initialization variable question</a>.</p>
  
  <p>Suppose we're dealing with this context:</p>
  
  <pre><code>object AppProperties {
  
     private var mgr: FileManager = _
  
     def init(config: Config) = {
       mgr = makeFileManager(config)
     }
  
  }
  </code></pre>
  
  <p>The problem with this code is that any other method in <code>AppProperties</code> might reassign <code>mgr</code>. Is there a technique to better encapsulate <code>mgr</code> so that it feels like a <code>val</code> for the other methods? I've thought about something like this (inspired by <a href="https://stackoverflow.com/questions/4400926/can-i-define-method-private-fields-in-scala/4401197#4401197">this answer</a>):</p>
  
  <pre><code>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))
     }
  
  }
  </code></pre>
  
  <p>... but this feels rather heavyweight to me (and initialization reminds me too much of C++ :-)). Any other idea?</p>