Search code examples
constructordartfinal

Why is this initialization of final fields wrong in Dart?


I have a simple class with two final fields, one of them is a map to store the data and another is a step function that updates the data when called:

class Data
{

  //for each name a list of observations
  final Map<String,List<double>> _dataMap;

  /**
   * the update step
   */
  final Step _updateStep;

Step is just a typedef.

Now, I want a constructor which has one parameter: a function that takes a reference Map<...> and returns a new Step. This seems logical to me, the updater needs a reference to the map to update it.

Why then this constructor fails?

  Data(Step initializer(Map<String,List<double>> dataReferences))
  : _dataMap = new Map(),
  _updateStep = initializer(_dataMap);

The error is in the second step

illegal implicit access to receiver 'this';

What? How does that leak this? How to fix it?


Solution

  • Günter Zöchbauer already explained the reason for your error.

    Here is a workaround:

    Data(Step initializer(Map<String,List<double>> dataReferences))
      : this._internal(initializer, new Map());
    
    Data._internal(initializer, map)
      : _dataMap = map,
        _updateStep = initializer(map);