Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to extend an object?

Tags:

scala

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?

like image 201
Jus12 Avatar asked Oct 02 '11 07:10

Jus12


People also ask

Can an object extend a class?

The question is quite self-explanatory. Classes all extend Object , and Object must be an object, since classes extend it.

What is object extend?

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.

Can an object extend a trait?

Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.

Can an object extend another object in Scala?

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.


1 Answers

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 } 
like image 69
Jens Schauder Avatar answered Oct 09 '22 07:10

Jens Schauder