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"
}
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"
}
}
The syntax of anonymous classes does not allow us to make them implement multiple interfaces. During construction, there might exist exactly one instance of an anonymous class. Therefore, they can never be abstract. Since they have no name, we can't extend them.
In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. Moreover an anonymous function provides a lightweight function definition. It is useful when we want to create an inline function.
To extend a class in Scala we use extends keyword. there are two restrictions to extend a class in Scala : To override method in scala override keyword is required. Only the primary constructor can pass parameters to the base constructor.
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With