I am programming in Flutter using Dart 2.1.0, and come across this situation:
mixin Salt {
final int pinches; // Immutable, and I want to delay initialization.
// Cannot declare constructors for mixin
}
class Meat with Salt {
Meat(int pinches) ... // How to initialize it?
}
Salt
has no constructor, so I cannot use initializer list. pinches
is final
, so I cannot set it in Meat
's constructor.
I don't want to make Salt
a class because Meat
may need to extend from something else.
And I want to keep pinches
immutable.
Any way to do it? Thanks in advance.
Either declare the function as static in your class or move it outside the class altogether. If the field isn't final (which for best practice, it should be, unless the field has to mutate), you can initialize it using a regular non-static method in the constructor body.
Immutable data constructs are those that cannot be mutated (altered) after they've been initialized. The Dart language is full of these. In fact, most basic variable types operate this way. Once created, strings, numbers, and boolean values cannot be mutated.
Immutable Data in Dart: Once made, strings, numbers, and boolean values can't be mutated. A string variable doesn't contain string data, itself.
A native Dart list is mutable, meaning you can change its items: var list = [1, 2];
You can change the declaration of your mixin to:
mixin Salt {
int get pitches;
}
And then define the field inside the implementation class
class Meat with Salt {
final int pitches;
Meat(this.pitches);
}
By design it is not possible to declare a final member into a mixin because it is not possible to declare a constructor for initializing the final member, citing the docs:
However, in this proposal, a mixin may only be extracted from a class that has no declared constructors. This restriction avoids complications that arise due to the need to pass constructor parameters up the inheritance chain.
A compromise may be to declare a private member and implement only a getter._pinches
is visible only inside the library, it is read-only for library users.
mixin Salt {
int _pinches;
get pinches => _pinches;
}
class Meat with Salt {
Meat(int pinches) {
_pinches = pinches;
}
}
Note: the above pattern, because of the visibility rules, works only if the mixin and the mixed classes reside in the same library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With