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");
menuBar.add(file);
JMenuItem open = new JMenuItem(new AbstractAction("Open Word Bank") {
    public void actionPerformed(ActionEvent e) {
        openWordBank();
    }
};
file.add(open);
But in Scala, it is done like:
menuBar = new MenuBar {
  contents += new Menu("File") {
    contents += new MenuItem(new Action("Open Word Bank") {
      def apply {
        openWordBank
      }
    })
  }
}
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.