Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is const optional in Dart 2?

Tags:

dart

dart-2

In Dart Object() constructor is declared as const so:

identical(const Object(), const Object()); //true

I know that in Dart 2 the keyword const is optional and I thought that the previous statement was equivalent to:

identical(Object(), Object()); //false

But actually it seems to be equivalent to:

identical(new Object(), new Object()); //false

Now my doubts are:

1) When is const keyword optional?

2) Is there any way to ensure instances of my classes to be always constant without const keyword? So that I can obtain:

indentical(MyClass(), MyClass()); //true (is it possible?)
like image 942
user1756508 Avatar asked Sep 30 '18 19:09

user1756508


2 Answers

Dart 2 allows you to omit new everywhere. Anywhere you used to write new, you can now omit it.

Dart 2 also allows you to omit const in positions where it's implied by the context. Those positions are:

  • Inside a const object creations, map or list literal (const [1, [2, 3]]).
  • Inside a const object creation in metadata (@Foo(Bar()))
  • In the initializer expression of a const variable (const x = [1];).
  • In a switch case expression (case Foo(2):...).

There are two other locations where the language requires constant expressions, but which are not automatically made constant (for various reasons):

  1. Optional parameter default values
  2. initializer expressions of final fields in classes with const constructors

1 is not made const because we want to keep the option of making those expressions not need to be const in the future. 2 is because it's a non-local constraint - there is nothing around the expression that signifies that it must be const, so it's too easy to, e.g., remove the const from the constructor without noticing that it changes the behavior of the field initializer.

like image 137
lrn Avatar answered Sep 29 '22 12:09

lrn


const is optional in a const context. Basically a const context is created when the expression has to be const to avoid compilation error.

In the following snippet you can see some place where const is optional:

class A {
  const A(o);
}

main(){
  // parameters of const constructors have to be const
  var a = const A(const A());
  var a = const A(A());

  // using const to create local variable 
  const b = const A();
  const b = A();

  // elements of const lists have to be const
  var c = const [const A()];
  var c = const [A()];

  // elements of const maps have to be const
  var d = const {'a': const A()};
  var d = const {'a': A()};
}

// metadatas are const
@A(const A())
@A(A())
class B {}

You can find more details in Optional new/const and Implicit Creation.

like image 43
Alexandre Ardhuin Avatar answered Sep 29 '22 13:09

Alexandre Ardhuin