I'm trying to get a better understanding of Scala, and I can't seem to find a valid usecase for code like the following:
class C extends { def m() { /* ... */ } }
What is the rationale for allowing such constructs?
Thanks!
extends: The extends keyword in Scala is used to inherit features of one class by another class. baseClass extends parentClass. This extends keyword is used to inherit class while creating a new one. With: the with keyword in Scala is used when we need to inherit more than one class by another class.
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.
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.
A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time. A regular class can extend a class and implement any number of interfaces simultaneously. But anonymous Inner class can extend a class or can implement an interface but not both at a time.
I guess the only rationale here is "avoid special cases if possible". You can extend any class, an anonymous class is a class, so you can extend an anonymous class.
That is not, in fact, an anonymous class! It's an early initializer and it runs as part of the constructor that goes before its superclass. Quoting the excellent answer from another stackoverflow question:
abstract class X {
val name: String
val size = name.size
}
class Y extends {
val name = "class Y"
} with X
If the code were written instead as
class Z extends X {
val name = "class Z"
}
then a null pointer exception would occur when Z got initialized, because size is initialized before name in the normal ordering of initialization (superclass before class).
It's called Early definitions and they deal with super class initialization order problem.
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