Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous Subclass in Scala

Tags:

scala

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

like image 543
Sudipta Deb Avatar asked Dec 20 '22 00:12

Sudipta Deb


2 Answers

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:

  1. Your client requires you to extend a given interface
  2. You register for multiple events at a time (for example a 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.

like image 157
gzm0 Avatar answered Jan 04 '23 20:01

gzm0


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).

like image 31
reggert Avatar answered Jan 04 '23 21:01

reggert