Skip to content

Commit

Permalink
Make clear that const constructors don't always create constant objec…
Browse files Browse the repository at this point in the history
…ts (#1119)
  • Loading branch information
kwalrath committed Sep 10, 2018
1 parent 5d64267 commit 7e36fdc
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
11 changes: 11 additions & 0 deletions examples/misc/test/language_tour/classes_test.dart
Expand Up @@ -168,4 +168,15 @@ void main() {

expect(pointAndLine1 == pointAndLine2, isTrue);
});

test('nonconst_const_constructor', () {
// #docregion nonconst-const-constructor
var a = const ImmutablePoint(1, 1); // Creates a constant
var b = ImmutablePoint(1, 1); // Does NOT create a constant

assert(!identical(a, b)); // NOT the same instance!
// #enddocregion nonconst-const-constructor

expect(a == b, isFalse);
});
}
29 changes: 23 additions & 6 deletions src/_guides/language/language-tour.md
Expand Up @@ -2308,12 +2308,12 @@ var p2 = new Point.fromJson({'x': 1, 'y': 2});
{% endprettify %}

<aside class="alert alert-info" markdown="1">
**Version note:** The `new` keyword became optional in Dart 2.
**Version note:** The `new` keyword became optional in Dart 2.
</aside>

Some classes provide constant constructors. To create a compile-time
constant using a constant constructor, put the `const` keyword
before the constructor name:
Some classes provide [constant constructors](#constant-constructors).
To create a compile-time constant using a constant constructor,
put the `const` keyword before the constructor name:

<?code-excerpt "misc/test/language_tour/classes_test.dart (const)"?>
{% prettify dart %}
Expand Down Expand Up @@ -2354,9 +2354,21 @@ const pointAndLine = {
};
{% endprettify %}

If a constant constructor is outside of a constant context
and is invoked without `const`,
it creates a **non-constant object**:

<?code-excerpt "misc/test/language_tour/classes_test.dart (nonconst-const-constructor)"?>
{% prettify dart %}
var a = const ImmutablePoint(1, 1); // Creates a constant
var b = ImmutablePoint(1, 1); // Does NOT create a constant

assert(!identical(a, b)); // NOT the same instance!
{% endprettify %}

<aside class="alert alert-info" markdown="1">
**Version note:** The `const` keyword became optional
within a constant context in Dart 2.
**Version note:** The `const` keyword became optional
within a constant context in Dart 2.
</aside>


Expand Down Expand Up @@ -2694,6 +2706,11 @@ class ImmutablePoint {
}
{% endprettify %}

Constant constructors don't always create constants.
For details, see the section on
[using constructors](#using-constructors).


#### Factory constructors

Use the `factory` keyword when implementing a constructor that doesn’t
Expand Down

0 comments on commit 7e36fdc

Please sign in to comment.