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