Sdk: Assert in forwarding constructor throws confusing runtime error

Created on 17 May 2019  路  3Comments  路  Source: dart-lang/sdk

The following code executes without problems:

main() {
  var foo = Foo(42);
  print(foo.bar);
}

class Foo {
  final int bar;

  Foo(int bar) : this._(bar);

  Foo._(this.bar) : assert(bar > 0);
}

But put the assert to the forwarding (default) constructor, and you hit a runtime error:

main() {
  var foo = Foo(42);
  print(foo.bar);
}

class Foo {
  final int bar;

  Foo(int bar) : assert(bar > 0), this._(bar);

  Foo._(this.bar);
}

Static analysis doesn't report anything, the program fails at runtime. The line in question has Error: Final field 'bar' is not initialized by this constructor. Try to initialize the field using an initializing formal or a field initializer. There is another error attached to line 1 of the file, saying Error: Can't have other initializers together with 'this'..

The second error is a little bit helpful, but it's not obvious what it relates to. When I saw it after a larger refactor, I was stumped. I don't consider asserts initializers, and I didn't know which line it related to.

Something like "You can't have asserts in this constructor because it forwards to another constructor. Put the assert there." would be helpful.

Dart VM version: 2.3.0 (Fri May 3 10:32:31 2019 +0200) on "macos_x64"
reproducible on https://dartpad.dartlang.org/ as of today

area-front-end front-end-missing-error type-bug

Most helpful comment

Why can't forwarding constructors have asserts?

All 3 comments

I've hit this error as well and I have to say this is SUPER confusing. Thanks @filiph !

Why can't forwarding constructors have asserts?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jmesserly picture jmesserly  路  3Comments

rinick picture rinick  路  3Comments

ranquild picture ranquild  路  3Comments

bergwerf picture bergwerf  路  3Comments

55555Mohit55555 picture 55555Mohit55555  路  3Comments