Suppose I have a trait in Scala
trait Connection { def init(name: String) def dispose } And I want to create a class which implements it. But I want to name it as Connection also:
class Connection extends Connection { // .... } It's not going to work. Of course, I could name trait something differently, but it turned out that the naming convention in Scala says that I should name trait as ordinary classes, meaning without any prefix, which I would use in C# (IConnection where IConnection would be the interface).
And in this particular case the name of Connection for the class and the trait is more suitable.
Or did I miss something in Scala's naming convention?
Naming-convention definitionA collection of rules followed by a set of names which allow users to deduce useful information, based on the names' character sequence and knowledge of the rules followed; such as Manhattan's East-West streets being called "Streets" and its North-South streets being called "Avenues". noun.
In Scala, we are allowed to implement the method(only abstract methods) in traits. If a trait contains method implementation, then the class which extends this trait need not implement the method which already implemented in a trait. As shown in the below example. Traits does not contain constructor parameters.
When to Use Traits? If the behavior will not be reused, then make it a concrete class. It is not reusable behavior after all. If it might be reused in multiple, unrelated classes, make it a trait.
The fact that you are extracting a general API into a Connection trait itself implies that it'll have multiple specific implementations. Those implementations will of course be related to some more specific entities, e.g. a MySQL or an H2 database.
There are several approaches to your problem depending on the chosen architecture of your app:
If you keep the specific implementations in the same namespace you get:
myApp.Connection
myApp.MySqlConnection
myApp.H2Connection
But the above is actually discouraged due to redundancy in names (the *Connection part) and introduction of a new package is recommended, e.g.:
myApp.Connection
myApp.connections.MySql
myApp.connections.H2
or
myApp.Connection
myApp.Connection.MySql
myApp.Connection.H2
if you choose to place the specific implemntation in a companion object of Connection.
In more advanced approaches to architecture you will end up with specific implementations having private packages:
myApp.Connection
myApp.mySql.Connection
myApp.h2.Connection
And even here although you have the Connection name clashing it's easily solvable due to types being located in different packages by using qualified references (myApp.Connection) or qualified imports:
import myApp.{Connection => GeneralConnection} //or IConnection if you insist 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