Thursday, April 25, 2019

Inheritance in Scala

Scala supports inheritence
- Code Reuse
- Specialization

Each class except for Any has exactly one super-class
- Non private members are inherited
- Non final members can be overridden

Subtype polymorphism
- Polymorph means having more than one types
- The Subclass type conforms to the superclass type

Subclass
Bird extends Animal

- default superclass is AnyRef
- can only extend one class

Final and Sealed Classes

- Use final to prevent a class from being extended

final class Animal

class Bird extends Animal (gives error)

Sealed classes can only be extended within the same source file
- Use it to create and algebric data type (ADT) called Tagged Union
- Example: Option with some and none

sealed class Animal

class Bird extends Animal
final class Fish extends Animal

Accessing superclass members

- Use super to extend superclass members


Uniform Access Principle
For a client it should make no difference, whether a property is implemented through storage or computation

- Properties can be implemented as def or as val

class Animal{
     def name: String = "Lion"
     val name: String = "Lion"
}

Overriding vals with def

- val is stable, but parameterless def could return different results on different calls
- We can decide to become stable and override a def with a val

class Animal {
    def name: Seq[char] = Random.shuffle("Lion".toSeq)
}

class Bird extends Animal {
    override val name: Seq[Char] = "Dog"
}
 

Lazy Vals

- All vals are initialized during object construction
- Use lazy keyword to defer initialization until first usage
- Lazy vals are not final - might show some performance drawbacks

lazy val lazyVame = {
   println("I am very lazy")
}


No comments:

Post a Comment