April 18, 2004 new+with sugar | ||||
---|---|---|---|---|
| ||||
In my little scripting language I have found the following extension to the new construct very useful. //-- make a little test class class Foo { float value; } //-- the sugar Foo foo=new Foo() { value=9; } Which is equivalent to going: Foo foo=new Foo(); with(foo) { value=9; } By itself it isn't too exciting, but when combined with operator overloading and anonymous functions it becomes an intuitive way to build hierarchial objects in a data desciption style. MenuBar menuBar=new MenuBar() { menus+=new Menu("File") { menus+=new MenuItem("New") { onClick=function(Menu menu){goNewFile();} } menus+=new MenuItem("Exit") { onClick=function(Menu menu){exit();} } } menus+=new Menu("Edit") { } } Another example: Widget widget=new Widget() { layout=new FlowLayout(); childs+=new Button("Hello") { onClick=function(Button button){printf("Hello");} } childs+=new Button("Exit") { onClick=function(Button button){exit();} } } |
Copyright © 1999-2021 by the D Language Foundation