Why only static fields can be declared as 'const'?

吃可爱长大的小学妹 提交于 2019-12-10 13:42:51

问题


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;

回答1:


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.



来源:https://stackoverflow.com/questions/17074897/why-only-static-fields-can-be-declared-as-const

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!