Explanation of mixin "on" clause is inaccurate #3769
Labels
a.language
Relates to the Dart language tour
d.enhancement
Improves docs with specific ask
e1-hours
Can complete in < 8 hours of normal, not dedicated, work
fix.examples
Adds or changes example
p2-medium
Necessary but not urgent concern. Resolve when possible.
st.triage.ltw
Indicates Lead Tech Writer has triaged
Page URL
https://dart.dev/guides/language/language-tour#adding-features-to-a-class-mixins
Describe the problem
The language tour says:
This isn't a great motivating example for using an
on
clause. The code would be better written as:Note here that the
MusicPerformer
mixin declares that it implementsMusician
even though it doesn't actually provide an implementation ofdance()
. Even so, it is able to calldance()
in its own body. That's the language ensures that when the mixin is applied to some class, the final resulting class does implementMusician
and thus the call todance()
will always succeed.This is better because an equally valid use of
MusicalPerformer
is:Note here that
SingerDancer
does not extend Musician. It provides its own implementation ofdance()
and declares that it itself implements Musician. In other words, the implementation ofdance()
doesn't have to be above MusicalPerformer in the class hierarchy. Here, it's below, and that's fine too.The
on
clause is only needed when a mixin contains a super call to some method, like:Here, the
on
clause is necessary because it's not enough for the class applying the mixin to provide it's own definition ofdance()
. Thedance()
method has to be above the mixin on the class hierarchy or thesuper.dance()
call will not be able to find it. Theon
clause ensures that any class applying the mixin must have some other class above the mixin that implements Musician.on
clauses are a weird, fairly rare feature. You only need them forsuper
calls in the mixin. In most cases where a mixin just doing a regular method call on itself, animplements
clause or defining the method as abstract in the mixin is what you want. You don't want to useon
clauses for those simple cases because then you take flexibility away from classes applying the mixin.Expected fix
I would explain using
implements
clauses and abstract method declarations in mixins to define what method calls the mixin's own methods are implemented in terms of. Then explain that if the mixin containssuper
calls, you can use anon
clause to specify what methods it is allowed to call.The text was updated successfully, but these errors were encountered: