diff --git a/examples/misc/test/language_tour/classes_test.dart b/examples/misc/test/language_tour/classes_test.dart index 2967fc98da..10a0579c21 100644 --- a/examples/misc/test/language_tour/classes_test.dart +++ b/examples/misc/test/language_tour/classes_test.dart @@ -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); + }); } diff --git a/src/_guides/language/language-tour.md b/src/_guides/language/language-tour.md index 0d4536706f..1e56e24352 100644 --- a/src/_guides/language/language-tour.md +++ b/src/_guides/language/language-tour.md @@ -2308,12 +2308,12 @@ var p2 = new Point.fromJson({'x': 1, 'y': 2}); {% endprettify %} -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: {% prettify dart %} @@ -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**: + + +{% 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 %} + @@ -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