Why a dart class constructor could have no body?

Viewed 258

I'm new to dart and came across code like below:

class Foo {
  Foo._internal();
  static final Foo instance = Foo._internal();
  // other stuff
}

I was confused by that the function _internal is called twice(in line2 and line3 respectively). Later I realized the first one is actually not an invocation but a definition of a constructor. It's just that the body of the definition is omited(allowing this is really bad a syntax rule of Dart IMHO).

So my question become that in what cases a function of dart can omit body?

1 Answers

Dart provides a lot of syntactic sugar for constructors, including the ability to use a semicolon in place of an empty constructor body. Since initialization lists should be preferred when possible, it's not uncommon for constructors to have empty bodies, so the shorthand is useful. Additionally, redirecting constructors and const constructors aren't allowed to have bodies at all.

Constructors aren't functions, so that shorthand does not apply to functions and methods in general. (As another example of a distinction between constructors and functions, only constructors can be used with new and const.) For methods, distinguishing between no body and an empty body is important:

abstract class AbstractInterface {
  void mustBeOverridden();

  void optionallyOverridden() {}
}

I agree that a constructor like Foo._internal(); looks weird, but I think it's not a common situation since it requires the intersection of a number of cases to make it look like a method call:

  • The class uses a named constructor.
  • That constructor takes no arguments.
  • That constructor does not use an initializer list.
  • That constructor does not use a constructor body.
Related