Sunday, January 11, 2015

Inheritance of Objects in Scala

Extending an object in Scala is not allowed due to the singleton semantics of objects. However, at times you may find yourself tempted to do so, e.g., to add some methods to an object. You have two choices to fulfill your requirement:

Refactoring. If possible, try to extract the interesting behaviors of the target object into an abstract trait, so that you can extend a trait instead of an object. This is also the standard solution in OOP textbooks.

Implicit conversion. You can make an object Y look like an extension of object X using implicit modifier:
object X { def a = 1 } 
object Y { def b = 2 }
implicit def YToX(y: Y.type) = X
println(Y.a) 
In this way, you can call methods on Y that were originally defined for X. Note that Y doesn't actually extend X, so there are still many big differences between this design and OO-inheritance. For example, you cannot override methods from X, you cannot substitute Y for X in your code, etc.

No comments:

Post a Comment