Sdk: package:meta: @mustCallSuper should not apply to 'implements'

Created on 7 Sep 2016  路  6Comments  路  Source: dart-lang/sdk

Example case:

import 'package:meta/meta.dart';

/// An interface for a living breathing animal on Earth.
///
/// Animals are different sizes and may need to eat more or less.
abstract class Animal {
  /// Eat [food]. Throws exception if the animal is still hungry after eating.
  @mustCallSuper
  void eat(Food food) {
    if (isHungry) {
      throw 'Was not fed enough food!';
    }
  }

  bool get isHungry;
}

In this example, I'd assume that extends Animal triggers a warning I missed super.eat:

class TinyAnimal extends Animal {
  bool _isHungry = false;

  @override
  void eat(Food food) {
    _isHungry = false;
  }

  @override
  bool get isHungry => _isHungry;
}

However, this will _also_ (incorrectly) trigger a warning. I _can't_ call super:

class LargeAnimal implements Animal {
  bool _isHungry = false;

  @override
  void eat(Food food) {
    if (!food.isLargeAmount) {
      throw 'Large animals need large amounts of food!';
    }
    _isHungry = false;
  }

  @override
  bool get isHungry => _isHungry;
}
P2 area-analyzer type-bug

All 6 comments

Either that, or there should also be a hint if a class that has methods annotated with @mustCallSuper is implemented.

@Hixie Any thoughts?

Yeah, this seems legit.

We should probably require that classes be annotate as @mixin or @interface to be used with "with" or "implements", which would address this somewhat, but that's another (already filed) bug.

In this specific case though I'd like Animal to be both implementable and extendable by default (Dart idioms that we see across the code base and I think are well respected). I could see the value of having @mixin (you _must_ mix me in) or @interface (you _must_ implement me), but I think those are somewhat separate.

Oh yeah I'm not saying this would be required. A package would have to opt-in to this kind of thing for sure.

Thanks Brian!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DartBot picture DartBot  路  3Comments

jmesserly picture jmesserly  路  3Comments

sgrekhov picture sgrekhov  路  3Comments

matanlurey picture matanlurey  路  3Comments

DartBot picture DartBot  路  3Comments