Add a hint `@nonVirtual` for class members

… or, to help developers when defining the intended use of a class, and to help users use a class properly (i.e. as intended by the class). I’d find this extremely useful when working on fairly complex classes with lots and lots of member fields and methods.

Similar to the spirit of @sealed (#27372):

import 'package:meta/meta.dart';

class X {
  @nonVirtual
  void alwaysPrintFoo() {
    print('Foo');
  }
}

class Y extends B {
  // HINT: X.alwaysPrintFoo is marked @nonVirtual and should not be overridden.
  void alwaysPrintFoo() {
    print('Bar');
  }
}

General concept:

  • Issue a hint when a member annotated with @nonVirtual is overriden.

Because of how this annotation would need to work, I imagine it would also need to:

  • Issue a hint when a class with one or more @nonVirtual members is implemented (implements – not extends/with), as by definition a class with @nonVirtual member requires the original implementation:

    import 'package:meta/meta.dart';
    
    class X {
      @nonVirtual
      void alwaysPrintFoo() {
        print('Foo');
      }
    }
    
    // HINT: Cannot implement a class with one or more `@nonVirtual` members.
    abstract class Y implements X {}
  • Issue a hint when an abstract member is annotated with @nonVirtual. Also impossible:

    import 'package:meta/meta.dart';
    
    abstract class X {
      // HINT: Cannot define a `@nonVirtual` abstract member.
      @nonVirtual
      void alwaysPrintFoo();
    }

/cc @davidmorgan @srawlins for thoughts.

Author: Fantashit

3 thoughts on “Add a hint `@nonVirtual` for class members

  1. I keep getting into situations where I’d like to have this functionality.

    For reference, an old school issue from @danrubel asking for language-level support of this is here: #3928. I’ll update that issue to link here. I do think it’s better (and more practical) to implement this via pkg:meta rather than having it in the language.

  2. It’s now October 2019, and this issue’s been open for over a year. can someone on the Dart team let us know what they think about this?

Comments are closed.