Why only static fields can be declared as 'const'?
Asked Answered
K

2

7

I just upgraded my Dart Editor (0.5.16_r23799), and code that was bug/warning free, is not anymore.

class Fubar {
  const BAR = 1000000;  
  Fubar(){   
  }
}

Lines beginning by const have marker and this message :

Only static fields can be declared as 'const'

I read this ch02-final-const, nothing there.

This post dart-const-static-fields says that const modifier implies static, if we can't use const without static, we should use final instead ?... but what doc/post I missed ? Intend to do this :

Fubar f = new Fubar();
some = f.BAR;
Katydid answered 12/6, 2013 at 20:38 Comment(0)
A
7

This is a recent change related in the Notes From the June 4 Dart Language Design Meeting :

const instance variables

Gilad's view is that they should work like statics except for scoping. Apparently, though, it's complicating the VM implementation of instance metadata. Three solutions:

  1. No const instance fields.
  2. Metadata is statically scoped.
  3. Try to do it correctly.

Lars likes 1. I say 1 simplifies things for users. Right now, people get confused with static final const etc. Gilad is OK with 1.

I asked if the syntax would be "static const" or just "const"? Users get confused when having to do "static" with constants.

Lars says they are confused because they don't understand the system. Requiring "static" will help them understand what's going on.

Ali answered 12/6, 2013 at 20:45 Comment(0)
U
0

The reason why you can't use const with fields of a class is because a constant field is created at compile time, a field belongs to an instance of a class (till you've explicitly added the static keyword) and that is created at runtime. You can't have the field created before the instance it belongs to. And so a field can't be made constant. Although a static field can be made constant as static fields are associated with a class and with classes; during compilation, the Dart compiler analyzes the class definitions and generates corresponding metadata and instructions. This means that you can have the static field (as part of the class definitions) constant (immutable) during compile time. So at runtime, it is already known that this particular field of the class is a constant.

Unobtrusive answered 17/5, 2023 at 15:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.