Anonymous subclass in Scala

I am trying to understand an anonymous subclass in Scala. I wrote the code below:

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 that I can not understand what are the customs / benefits of Anonymous subclass in Scala. If you have any questions, please share them. Thanks.

Regadrs, Sudipta

+4
source share
2 answers

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 => /* do something */) 

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.

+9
source

Anonymous classes in Scala, Java, and almost any other language that supports them are useful when you need to pass an instance of some interface or base class as an argument to a function, and you never need to use the same implementation elsewhere in your code .

Note that only members and methods 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 sayGoodbye methods can only be called by printMyName or the constructor of the anonymous class, since no one knows about them because they are not declared in the base class (Person).

+2
source

Source: https://habr.com/ru/post/1502273/


All Articles