Is there a way to extends another class from an Anonymous class in Scala? I means something like
abstract class Salutation {
def saybye(): String = \"Bye\"
Yep, and it looks pretty much the same as it does in Java:
abstract class Salutation {
def saybye: String = "Bye"
}
val hello = new Salutation {
def sayhello: String = "hello"
}
val hi = hello.sayhello
val bye = hello.saybye
If Salutation
is an abstract class or trait with a sayhello
method with the same signature, you'll have provided an implementation; otherwise you'll have created an instance of an anonymous structural type:
hello: Salutation{def sayhello: String}
Note that calls to the sayhello
method involve reflection (because of the way structural types are implemented in Scala), so if you're using this method heavily you should probably define a new trait or class.