In scala, we cannot extend object
:
object X object Y extends X
gives an error error: not found: type X
In my case someone has defined some functionality in an object and I need to extend it (basically add another method). What would be the easiest way to extend this object?
The question is quite self-explanatory. Classes all extend Object , and Object must be an object, since classes extend it.
Prototype - Object extend() MethodThis method copies all properties from the source to the destination object. This is used by Prototype to simulate inheritance by copying to prototypes.
Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.
Limitations of Scala ObjectYou cannot extend an object to create a class or another object. Objects cannot have a public constructor. And that makes sense as well. Because they are singleton objects and you don't want to use them as a blueprint to instantiate new objects.
As so often the correct answer depends on the actual business requirement. Extending from an object would in some sense defy the purpose of that object since it wouldn't be a singleton any longer.
What might be a solution is to extract the behavior into an abstract trait. And create objects extending that trait like so:
trait T{ // some behavior goes here } object X extends T object Y extends T { // additional stuff here }
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