title: Dart: How to efficiently initialize multiple final fields that depend on the same calculation?
body: <p>I have a Dart class with multiple fields that have to be <code>final</code>, because the class extends another class marked with <code>@immutable</code>.
  The values of these fields are supposed to be calculated when an instance of the class is created. In Dart, "final instance variables must be initialized before the constructor body starts" (<a href="https://www.dartlang.org/guides/language/language-tour#final-and-const" rel="noreferrer">from dartlang.org</a>).
  In that scope, you can only call <code>static</code> methods.</p>
  
  <p>That works for me except some fields depend on the same calculation, meaning that <em>the same calculation is done twice</em>.
  Is there any way to avoid that, i.e. by saving some temporary result?</p>
  
  <p>My current code:</p>
  
  <pre><code>class _IntegralCurve extends Curve {
    static double delta = 0.01;
  
    _IntegralCurve(this.original) :
        integral = calculateIntegral(original),
        values = calculateNormalizedValues(original);
  
    final Curve original;
    final double integral; // Accessible to other classes.
    final Map&lt;double, double&gt; values;
  
    /// Does the actual integrating work. Called twice.
    static Map&lt;double, double&gt; integrate(Curve original) {
      double integral = 0.0;
      final values = Map&lt;double, double&gt;();
  
      for (double t = 0.0; t &lt;= 1.0; t += delta) {
        integral += original.transform(t) * delta;
        values[t] = integral;
      }
      values[1.0] = integral;
      return values;
    }
  
    /// Calculates the integral.
    static double calculateIntegral(Curve curve) =&gt; integrate(curve)[1];
  
    /// Calculates cumulative values.
    static Map&lt;double, double&gt; calculateNormalizedValues(Curve curve) {
      final values = integrate(curve);
  
      for (final double t in values.keys) {
        values[t] = values[t] / values[1];
      }
      return values;
    }
  
    double transform(double t) {
      for (final key in values.keys)
        if (key &gt; t)
          return values[key];
      return values[1.0];
    }
  }
  </code></pre>