dart - Failed enum attempt -


i porting library heavily based on java enums , need code own enum until there native support them.

however fail!

in code below chesscolor.values() method returns null , can't see why.

however new dart ...

there must static fields , initialization have missed ...

enum base class

part of chessmodel;  /**  * emulation of java enum class.  */ abstract class enum {        final int code;   final string name;    enum(this.code, this.name);        tostring() => name;      } 

a simple usage try

part of chessmodel;  final chesscolor white = chesscolor.white; final chesscolor black = chesscolor.black;  class chesscolor extends enum {    static list<chesscolor> _values;   static map<string, chesscolor> _valuebyname;    static chesscolor white = new chesscolor._x(0, "white");   static chesscolor black = new chesscolor._x(1, "black");    chesscolor._x(int code, string name) : super (code, name) {     if (_values == null) {       _values = new list<chesscolor>();       _valuebyname = new map<string, chesscolor>();     }     _values.add(this);     _valuebyname[name] = this;   }    static list<chesscolor> values() {     return _values;   }    static chesscolor valueof(string name) {     return _valuebyname [name];   }      chesscolor opponent() {         return == white ? black : white;     }      bool iswhite() {         return == white;     }      bool isblack() {         return == black;     }  } 

if absolutely need emulate old java enum pattern, can. however, dart looks @ enums more simple construct.

to answer 1 of questions, static fields initialized "lazily", in initialized on first access.

that being said, here's 1 way can implement trying do. use const constructors create const objects. const objects canonicalized compiler. means 2 const objects initialized in same way in fact same exact object. generally, want enums const.

/**  * emulation of java enum class.  */ abstract class enum {        final int code;   final string name;    const enum(this.code, this.name);        string tostring() => name; }  final chesscolor white = chesscolor.white; final chesscolor black = chesscolor.black;  class chesscolor extends enum {    static const list<chesscolor> values =       const [chesscolor.white, chesscolor.black];   static map<string, chesscolor> valuebyname =       const {"white": chesscolor.white, "black": chesscolor.black};    static const chesscolor white = const chesscolor._x(0, "white");   static const chesscolor black = const chesscolor._x(1, "black");    const chesscolor._x(int code, string name) : super (code, name); }  void main() {   print(white);   print(chesscolor.values);   print(chesscolor.white.code);   print(chesscolor.valuebyname['black']); } 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -