2. Trait can define abstract or concrete fields/methods.
If a class extends the trait, You don’t need to use the override keyword to override a var field in a subclass (or trait), but you do need to use it to override a val field.
3. If a class extends a trait without implementing its abstract methods/fields, it must be defined as abstract class.
4. Any concrete class that mixes in the trait must ensure that its type conforms to the trait’s self type
In other words, A trait and a class the trait will be mixed into should both have the same superclass.
If a class extends multiple traits, use
For example, T can only be mixed into classes C that extend a type P, where P may be a trait, class, or abstract class:If a class extends multiple traits, use
extends
for the first trait and with
to extend (mix in) the other traits.trait T extends P
class C extends P with T
5. To make sure a trait named MyTrait can only be mixed into a class that is a subclass of a type named BaseType.
trait MyTrait {
this: BaseType =>
//more code here
}
class MyClass extends BaseType with MyTrait
6. Fields of a trait can be declared as either
var
or val
. You don’t need to use the override
keyword to override a var
field in a subclass (or trait), but you do need to use it to override a val
field.Scala lets you use the
_
wildcard instead of a variable name when the parameter appears only once in your functionAlthough Scala has abstract classes, it’s much more common to use traits than abstract classes to implement base behavior. A class can extend only one abstract class, but it can implement multiple traits, so using traits is more flexible.
No comments:
Post a Comment