CarrKnight
CarrKnight

Reputation: 2928

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?

Upvotes: 3

Views: 4080

Answers (2)

Florian Loitsch
Florian Loitsch

Reputation: 8128

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);

Upvotes: 6

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657348

You are reading from _dataMap (initializer(_dataMap)). _datamap is a field of this it is not an argument. You can't read fields from 'this' in constructor initializers as the error message says.

Upvotes: 3

Related Questions