Home > OS >  specify variable as some kind of enum in dart
specify variable as some kind of enum in dart

Time:11-24

Here's a little fun class:

abstract class Concept {
  late Enum option;
  String get name => option.name;
}

and you might implement it like this:

enum FeeOption {
  fast,
  standard,
  slow,
}
class FastFeeRate extends Concept {
  FeeOption option = FeeOption.fast;
}
print(FastFeeRate().name); // 'fast'

but then you get an error:

FastFeeRate.option=' ('void Function(FeeOption)') isn't a valid override of 'Concept.option=' ('void Function(Enum)').

So, how do you specify a variable as any kind of enum, not Enum itself?

CodePudding user response:

Your class Concept has a mutable (late, but that doesn't matter) field with type Enum. That means it has a setter named option= with an argument type of Enum.

The subclass FastFeeRate is a subclass. It has another field (your class has two fields!) also named option, which has a setter with an argument type of FastFeeRate.

That's not a valid override. The subclass setter must accept all arguments that the superclass setter does, but it doesn't accept all Enum values.

What you might have intended to do is:

abstract class Concept<T extends Enum> {
  T option;
  Concept(this.option);
  String get name => option.name;
}
class FastFeeRate extends Concept<FeeOption> {
  FastFeeRate() : super(FeeOption.fast);
}

or

abstract class Concept<T extends Enum> {
  abstract T option;
  String get name => option.name;
}
class FastFeeRate extends Concept<FeeOption> {
  FastFeeRate option = FeeOption.fast;
}

depending on whether you want to define the field in the superclass or the subclass (but make sure to only define a concrete field in one of them).

  • Related