3

The analyzer doesn't say final var is illegal. but dart2js says final var is illegal

What is correct? Why?

0xcaff
  • 13,085
  • 5
  • 47
  • 55
Sungguk Lim
  • 6,109
  • 7
  • 43
  • 63

2 Answers2

5

That is probably a bug in the analyzer. final and var are mutual exclusive.

One of the following is allowed

  • final identifier
  • final type identifier
  • const identifier
  • const type identifier
  • var identifier
  • type identifier

Dart Programming Language Specification (1.2) - Variables

finalConstVarOrType:
   final type?
   | const type?
   | varOrType
   ;
varOrType:
   var
   | type
   ;

EDIT

My DartEditor (Dart VM version: 1.3.0-dev.3.2 (Mon Mar 10 10:15:05 2014) on "linux_x64") shows an error for final var xxx (Members can not be declared to be both 'final' and 'var'.)

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • yeah thank you for answer this, kind @Günter Zöchbauer :) by the way, I am not able to understand why `var` is not allowed by specification. Perhaps, the type is not fixed at compile time? – Sungguk Lim Mar 13 '14 at 06:19
  • @sunglim `var` specifies that the field allows any type but if the field is `final` it can have only one type - the type of the value it gets initialized with, therefore this two keywords conflict with each other (just my opinion, I have no special insight to the decision make process that took place) – Günter Zöchbauer Mar 13 '14 at 06:38
  • 1
    @sunglim It's much easier. The keyword `var` means mutable variable. The keyword `final` means `val`, immutable variable, or just a value that are not a `const` value but it also are not a mutable. Not a `const` because it has `runtime storage` but at the same time this is just an immutable `value` that stored. Now consider this code: `final var foo` this is the same as `val var foo`. As you can see this is not possible at once declare variable as mutable and immutable. – mezoni Mar 13 '14 at 07:43
5

The keyword var means mutable variable with explicit dynamic type specifier. The explicit type specifier means that this is not possible specify another type in declaration.

The keyword final means val or immutable variable with unspecified type, with implicit dynamic type. The implicit type specifier means that this is possible specify other type in declaration.

More precisely variable that declared as val are the value and variable at once.

It are variable because has the runtime storage.

But it are also immutable value that can be retrieved from associated storage just once and can be used anywhere.

Now consider the following code:

final var foo;

This is the same as the following pseudo code:

immutable mutable dynamic foo;

Of course, this will not work.

mezoni
  • 10,684
  • 4
  • 32
  • 54