Friday, 9 January 2015

Traits in Scala

1. Classes extend a trait or a class, the first one uses "extends", the others use "with"

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 extends for the first trait and with to extend (mix in) the other traits.
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:

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.
trait PizzaTrait {
  val maxNumToppings: Int
}

class Pizza extends PizzaTrait {
  override val maxNumToppings = 10  // 'override' is required
}


Scala lets you use the _ wildcard instead of a variable name when the parameter appears only once in your function

Although 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