有没有办法从Scala中的Anonymous类扩展另一个类?我的意思是
abstract class Salutation {
def saybye(): String = "Bye"
}
class anotherClass() {
def dummyFunction() = {
val hello = new {
def sayhello(): String = "hello"
} extends Salutation
val hi = hello.sayhello //hi value is "Hello"
val bye = hello.saybye //bye value is "bye"
}
}
Run Code Online (Sandbox Code Playgroud)
是的,它看起来和Java一样:
abstract class Salutation {
def saybye: String = "Bye"
}
val hello = new Salutation {
def sayhello: String = "hello"
}
val hi = hello.sayhello
val bye = hello.saybye
Run Code Online (Sandbox Code Playgroud)
如果Salutation是具有sayhello相同签名的方法的抽象类或特征,则您将提供实现; 否则你将创建一个匿名结构类型的实例:
hello: Salutation{def sayhello: String}
Run Code Online (Sandbox Code Playgroud)
请注意,对sayhello方法的调用涉及反射(因为结构类型在Scala中的实现方式),因此如果您大量使用此方法,则应该定义新的特征或类.
| 归档时间: |
|
| 查看次数: |
5052 次 |
| 最近记录: |