Scala 中的匿名子类 [英] Anonymous Subclass in Scala
问题描述
我正在尝试理解 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)
}
但是我无法理解 Scala 中匿名子类的用法/优点是什么.如果您有任何意见,请在这里分享.谢谢.
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.
各位,苏迪普塔
推荐答案
在 Scala 中使用匿名子类与使用 Java 中的匿名子类.Java 中最常见的用法可能是 观察者模式,如第一个链接所示.
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.
该示例直接转换为 Scala:
The example directly translates to Scala:
button.addActionListener(new ActionListener() {
def actionPerformed(e: ActionEvent) {
// do something.
}
});
但是,在 Scala 中,您可能更愿意为此使用匿名函数(如果库允许您这样做):
However, in Scala you would probably rather use an anonymous function for that (if the library allows you to):
button.addActionListener(e => /* do something */)
在 Scala 中,在这种情况下,您可能会使用匿名子类,如果:
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.
这篇关于Scala 中的匿名子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!