A practical guide to Scala Traits
Trait
- has a super class of AnyRef
- uses extends or with for inheriting a trait (with to inherit multiple traits)
- defines a type
- can be overridden using override keyword
Trait vs Interface (Java)
- trait can declare fields and main state
- rich vs thin interfaces (every concrete method added to trait makes it richer)
Trait vs Class
- trait can NOT have any class parameters
trait doesn't support coding in this style: class Point(x: Int, y: Int)
- super calls are statically bound in classes, but dynamically bound in trait
super.toString is predicable in classes, but not in trait when mixing
Ordered Trait
Traits as stackable modifications
- order of mixins: right most trait takes effect first
When to use Trait?
- If the behaviour will not be reused, then make it a concrete class
- If it might be reused in multiple, unrelated classes, make it a trait
- If you want to inherit from it in Java code, use an abstract class
- If you plan to distribute it in compiled form, and you expect outside groups to write classes inheriting from it, you might lean towards using an abstract class
- If efficiency is very important, lean towards using a class
- If you still do not know, after considering the above, then start by making it as a trait
Comments
Post a Comment