Using anonymous subclasses in Scala is no different than using anonymous subclasses in Java . The most common use in Java is possible in the observer pattern , as shown in the first link.
The example directly translates to Scala:
button.addActionListener(new ActionListener() { def actionPerformed(e: ActionEvent) { // do something. } });
However, in Scala, you would most likely use an anonymous function for this (if the library allows you):
button.addActionListener(e => )
In Scala, you can use anonymous subclasses in this case if:
- Your client requires you to extend this interface
- You register for several events at a time (e.g.
java.awt.MouseListener
)
These, of course, are only examples. Anywhere where you do not call a class a class, you can use an anonymous (optional) class.
gzm0 source share