Java interop errata

13 08 2008

There are a few possibilities for improvement on this Scala Swing Example.

  • Removed unnecessary semi-colons
  • Inlined import
  • Removed = in main declaration (strongly advised on functions returning Unit and especially more for main)
  • Removed a few unnecessary parentheses
import javax.swing._
import java.awt.event.{ActionEvent, ActionListener}

object HelloWorld extends JFrame("Hello Swing") {
  def showButtonMessage(msg: String)  =
    JOptionPane.showMessageDialog(null, String.format("""Hello from Scala. Button %s pressed""", Array(msg)));

  def main(args: Array[String]) {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    val button = new JButton("Click Me")
    button.addActionListener((e:ActionEvent) => showButtonMessage(e.getActionCommand.toString))
    getContentPane add button
    pack
    setVisible(true)
  }

  implicit def actionPerformedWrapper(func: (ActionEvent) => Unit) = new ActionListener {
    def actionPerformed(e:ActionEvent) = func(e)
  }
}

Actions

Information

2 responses

13 08 2008
Jeff

Hi Tony

Could you explain what difference the equals sign makes in a function definition and why it is strongly advised to remove when returning Unit.

Thanks
Jeff

15 08 2008
Tony Morris

Hi Jeff,
When you omit =, the method is guaranteed to be of the type Unit. This puts an additional type-check in place so that you don’t do something like call List.remove as the last statement expecting it to be a side-effect.

It becomes more important for main, since you have no type checks in place at the call site. You’ll just get a runtime error instead (no such method main).

Leave a comment