Skip to content

How should non-nullability handle fields that are initialized after object creation? #146

@leafpetersen

Description

@leafpetersen

A pattern that comes up with some frequency is to have fields in an object which is not initialized in the constructor (or at least not in the initializer list), but which should never be observed to be null once some further initialization is done. How should Dart with non-nullable types handle this? Some options that have been used in other languages:

  • Kotlin style lateinit: mark a field as "will be initialized before use". The programmer writes the code as if it is non-nullable, and the compiler checks uses that it can't prove are safe.
  • Swift style implicitly unwrapped types. Swift allows you to mark a type as nullable, but allowed to be accessed as non-nullable.
  • Pre-post conditions on methods (allow methods to specify in some way that they initialize certain fields, and other methods to specify that they require certain fields to be initialized).

cc @lrhn @eernstg @munificent

Metadata

Metadata

Assignees

Labels

nnbdNNBD related issues

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions