Thursday, April 25, 2019

Scala Traits

On JVM Single inheritence - Traits in Scala overcomes this limitation.

abstract class Animal

class Bird extends Animal {
    def fly: String = "I am flying"
}

class Fish extends Animal {
   def swimming: String = "I am swimming"
}

class Duck //Got stuck here

trait Swimmer {
  def swimming: String = "I am swimming"
}

- Traits may contain concrete and abstract members
- Traits are abstract and cannot have parameters
- Like classes, traits extend exactly one superclass


Mix-In composition

- The extends either creates a subclass or mixes in the first trait
- The with mixes in subsequent traits
- First keyword has to be extends regardless whether a class or a trait, then use with for further mix-ins
- Mixing in traits, means extending the superclass of the trait

class Fish extends Animal with Swimmer
class Duck extends Bird with Swimmer

trait Foo extends AnyRef
trait Bar extends AnyRef with Foo


Traits Linearization

- Scala takes the class and all of its inherited classes and mixed-in traits and puts them in a single, linear order. Therefore it is always clear what super means:



Inheritence Hierarchy

- Traits must respect the inheritance hierarchy - i.e. a class must not extend two incompatible super classes

scala> class Foo; class Bar; trait Baz extends Foo
defined class Foo
defined class Bar
defined trait Baz

scala> class Qux extends Bar
defined class Qux

scala> class Qux extends Bar with Baz
<console>:14: error: illegal inheritance; superclass Bar
 is not a subclass of the superclass Foo
 of the mixin trait Baz
       class Qux extends Bar with Baz
                                  ^

Concrete Members

- If multiple traits defined the same member, must use override




No comments:

Post a Comment