One of the many cool features in Scala are traits. traits are like a mixture of abstract classes and interfaces: You can 'implement' as many of them as you want just as with interfaces, but they can also contain implementation, which makes them similar to abstract classes. You also can't instantiate a trait on its own, so there is another similarity to abstract classes.
While digging my way through various libraries I found a couple of different usage patterns, how traits are getting used. Here is what I found so far:
The Steam Roller Trait: What happens when you drive a steam roller over something small, let's say an interface? It gets very wide. This is another technique used in the Scala Collection API. The trait defines a self type, either using another trait or a structural type and defines lots of other stuff based on that interface. This completely solves one of the basic challenges in Java interface design: If you define wide interfaces, i.e. interfaces with lots of methods, it increases the chances for users to find the method they need. On the other hand those poor bastards who have to implement such an interface have a lot of work to do. If you have any doubts how powerful this pattern is, check out how little code you have to write in order to create a new collection implementation which nicely integrates with all the others and has hundreds of methods just like all the other Scala collections as well.
Wan't to meet me in person to tell me how stupid I am? You can find me at the following events:
- Spring Data JDBC - New Kid on the block.
- Softwaredevelopment in the 21st century.
- Domain Driven Design mit Relationalen Datenbanken und Spring Data JDBC.
- Kerbal Space Program, Glücksspiel und Psychologie und was das mit dem (Berufs)leben zu tun hat.
- Javaland Freeletics
- Domain Driven Design mit relationalen Datenbanken und Spring Data JDBC
- The New Kid on the Block: Spring Data JDBC