Saturday, August 10, 2013

Beauty of Scala: construction of hierarchical objects

In Java, one would construct a GUI (e.g., Swing) like:
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem open = new JMenuItem(new AbstractAction("Open Word Bank") {
    public void actionPerformed(ActionEvent e) {
But in Scala, it is done like:
menuBar = new MenuBar {
  contents += new Menu("File") {
    contents += new MenuItem(new Action("Open Word Bank") {
      def apply {
That's the beauty of Scala! The code can be written like that because we can write initialization code (usually inside a constructor in Java) directly inside a Scala class.