Is this a good style with a line and an equally named object that extends that line?

While I was browsing through the Paul Phillips GitHub repositories, I noticed that it often uses a specific structur:

trait A { // ... } object A extends A 

For example: scala -improvement, strings Firstly, based on Java, I did not know about the same name for the attribute and object in the same area.
And now I ask, why is this useful? What are the advantages over direct identification of an object with all the attributes? Well, I know that this trait can be mixed, but I suppose to use only the object in practice.

+7
source share
3 answers

At least one case where this template comes in handy is when you create a library of functions. You can rearrange functions (actually methods, but let them use them in this context) in a few ways (which can then be considered modules), say, MyLibA , MyLibB , MyLibC , etc. Then, if for each of them you define an object that implements it, users of your library can easily use it by writing, for example:

 import mypackage.MyLibA._ 

(assuming mypackage is a containing package). In addition, you can easily provide a way to import all the functions of your lib by providing a MyLib object as follows:

 object MyLib extends MyLibA with MyLibB with MyLibC 

and then users can simply import mypackage.MyLib._ instead of writing an import for each module separately. Even better, you can define package object mypackage extends MyLibA with MyLibB with MyLibC , and then users just write import mypackage._ . And the bonus is that discerning users who would like to import only MyLibA and MyLibB on one line can also freely define their own “import object”, perhaps even filling it with their own utility functions or overriding their own

 object UserLibImport extends MyLibA with MyLibB { def userAdditionalFunction = /* ... */ override def someRedefinedLibAFunction = /* ... */ } 

... and then import it all with import UserLibImport._

So, I would say, in this case, this is not only a good style, it is strongly recommended to provide your functions in this way, since it provides maximum flexibility.

(This has also been briefly described in this answer .)

+10
source

An object is an obvious choice if you want to use the global singleton for utility methods. Unlike Java statics, you can pass this object as an instance of this trait.

One advantage is that you can create another instance of this attribute / interface for use in unit tests. It is very convenient if you are in TDD / BDD, statics was often a pain in the neck when it came to checking.

+3
source

Trade can be reused. Titus simply defines the contract of object A and may be some implementation. But this trait can be used for Mock objects and, as discussed above, for aggregating functionality.

0
source

All Articles