title: field initialization and constructor sequence in Scala with inheritance
body: <p>Say I have a class <code>Graph</code> and a subclass <code>MyGraph</code>, <code>Graph</code> has a method <code>build</code> allowing subclass to define its own build process.</p>
  
  <p>In <code>MyGraph</code>, I declare a field <code>node</code> which should be init in the build method. Thus I declare it to be null. However, when I create a <code>MyGraph</code> instance, the execution sequence first go to <code>MyGraph.build</code> and then <code>var node : Node = null</code>, which leaves the node to be null.</p>
  
  <p>What is the correct way to init such a field in a method invoked from the parent?</p>
  
  <pre><code>class Graph {
      def build:Unit = Unit
      build
  }
  
  class MyGraph extends Graph {
      var node : Node = null
      override def build:Unit = {
          node = new Node
      }
  }
  </code></pre>
  
  <p>[EDIT] More Detail about my use case: the Graph class represents a Computational Graph, which contains nodes for computation tasks. The graph has some inputs and one output. In sub classes, I need to expose the input node for user to provide input data. Here's some code providing more detail.</p>
  
  <pre><code>class Graph {
      val inputs = new ArrayBuffer[InputNode]()
      var output: Node = null
  
      def build:Unit = Unit
      build
  
      def newInput(): InputNode = {
          val in = new InputNode()
          inputs += in
          in
      }
  
      def setOutput(out: Node) {
          this.output = out
      }
  
      def compute():Unit = {
          inputs.foreach(_.computeAndForward())
      }
  }
  
  class LinearRegGraph extends Graph {
      var w : InputNode = null
      var x : InputNode = null
      var b : InputNode = null
  
      override def build:Unit = {
          w = newInput()
          x = newInput()
          b = newInput()
          val mul = new MulNode(w,x)
          val add = new AddNode(mul, b)
          setOutput(add) 
      }
  }
  
  object Main extends App {
      val graph = new LinearRegGraph()
  
      graph.x.setData(...)
      graph.w.setData(...)
      graph.b.setData(...)
  
      graph.compute()
      graph.output.getData()
  }
  </code></pre>
  
  <p>I currently use the following temporary solution. However, this code is vulnerable to the implementation of node building sequence and I don't like it.</p>
  
  <pre><code>class LinearRegGraph extends Graph {
      def w = inputs(0)
      def x = inputs(1)
      def b = inputs(2)
  
      override def build:Unit = {
          val w = newInput()
          val x = newInput()
          val b = newInput()
          val mul = new MulNode(w,x)
          val add = new AddNode(mul, b)
          setOutput(add) 
      }
  }
  </code></pre>