I am trying to understand Anonymous subclass in Scala. I have written the below code:
package com.sudipta.practice.chapter8
class Person(val name: String) {
def printMyName = println("Name: " + name)
}
class AnonymousSubclass(val name: String) {
val anonymousSubclass = new Person(name){
def sayHello = "Hello, " + name
def sayBye = "Bye, " + name
override def printMyName = println("My name is: " + name)
}
}
object testPerson extends App {
def printAnonDetails (myObject: AnonymousSubclass) = {
myObject.anonymousSubclass.printMyName
}
val personObject = new Person("Sudipta")
personObject.printMyName
val anonObject = new AnonymousSubclass("Sudipta")
printAnonDetails(anonObject)
}
But what I am not able to understand what are the usages/advantages of Anonymous Subclass in Scala. If you have any points, please share here. Thanks.
Regadrs, Sudipta
The use of anonymous subclasses in Scala is no different than the use of anonymous subclasses in Java. The most common use in Java is probably 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 probably rather use an anonymous function for that (if the library allows you to):
button.addActionListener(e => /* do something */)
In Scala you might use anonymous subclasses in this case, if:
java.awt.MouseListener
)These are of course only examples. In any location where not naming a class makes sense to you, you may use an anonymous (sub)class.
Anonymous classes in Scala, Java, and pretty much any other language that supports them are useful in cases where you need to pass an instance of some interface or base class as an argument to a function, and you will never need to use the same implementation anywhere else in your code.
Note that only members and methods that are defined by the interface or base class that your anonymous class implements/extends will be visible outside the anonymous class. In your example, this means that your sayHello
and sayBye
methods can only be called by anonymous's overrided printMyName (if this method need to call them), or the anonymous class's constructor, since nobody else outside the anonymous class will be able to know about them, as they are Not declared in the base class (Person).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With