Inheritance And Traits


Published on

Published in: Technology, Business
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Inheritance And Traits

  1. 1. Introducing Inheritance And Traits In Scala Piyush Mishra Software Consultant Knoldus Software LLP
  2. 2. Topics CoveredInheritanceTraitsMix-In Composition of traits into classesOrdered TraitsTraits as Stackable modificationOption Pattern
  3. 3. InheritanceInheritance is a way by which an object of a class acquire properties and behavior of object of other class. So Inheritance is used for code reuse.In Scala we use “extends” keyword to inherit properties and behavior extendsfrom a class.This is same as Javaclass Animalclass Bird extends AnimalOmitting extends means extends AnyRef
  4. 4. Calling superclass constructorSubclasses must immediately call their superclass constructor scala> class Animal(val name: String)defined class Animalscala> class Bird(name: String) extends Animal(name)defined class Bird
  5. 5. Use the keyword final to prevent a class from being subclassedScala> final class Animaldefined class AnimalScala> class Bird extends Animal<console>:8: error: illegal inheritance from final class Animal
  6. 6. Use the keyword sealed to allow sub-classing only within the same source filesealed class Animalclass Bird extends Animalclass Fish extends AnimalThis means, that sealed classes can only be subclassed by youbut not by others, i.e. you know all subclasses
  7. 7. Use the keyword override to override a superclass memberclass Animal {val name = "Animal"}class Bird extends Animal {override val name = "Bird"}
  8. 8. Abstract classes Use the keyword abstract to define an abstract classabstract class Animal {val name: Stringdef hello: String}
  9. 9. Implementing abstract membersInitialize or implement an abstract field or method to make it Concrete class Bird(override val name: String) extends Animal { override def hello = "Beep" }
  10. 10. Traits Traits are like Interfaces but they are richer than Java InterfacesThey are fundamental unit of code reuse in Scala They encapsulates method and field definitions, which canbe reused by mixing them in classesUnlike class inheritance a class can mix any number of traitsUnlike Interfaces they can have concrete methods
  11. 11. Unlike Java interfaces traits can explicitly inherit from a classclass Atrait B extends A
  12. 12. Mix-In Compotition One major use of traits is to automatically add methods toclass in terms of methods the class already has. That is, trait can enrich a thin interface,making it into a rich interface.trait Swimmer {def swim() {println("I swim!")}}Use the keyword with to mix a trait into a class that alreadyextends another classclass Fish(val name: String) extends Animal with SwimmerSo method swim can mix into class Fish ,class Fish does notneed to implement it.
  13. 13. Mixing-in multiple traitsUse the keyword with repeatedly to mix-in multiple traitsTrait ATrait BTrait CClass D extends A with B with CIf multiple traits define the same members, the outermost (rightmost) one “wins”
  14. 14. Ordered Trait When-ever you compare two objects that are ordered, it isconvenient if you use a single method call to ask about theprecise comparison you want. if you want “is less than,” you would like to call < if you want “is less than or equal,” you would like to call <= A rich interface would provide you with all of the usual comparison operators, thus allowing you todirectly write things like “x <= y”.
  15. 15. Ordered TraitWe have a class Numberclass Number(a:Int) {val number =adef < (that: Number) =this.number < that.numberdef > (that: Number) = this.number > that.numberdef <= (that: Number) = (this < that) || (this == that)def >= (that: Number) = (this > that) || (this == that)}
  16. 16. Ordered TraitWe have a class Number which extends ordered traitclass Number(a:Int) extends Ordered[Number] { val number=a def compare(that:Number)={this.number-that.number}}So compare method provide us all comparisonoperators
  17. 17. Traits as stackable modifications Traits let you modify the methods of a class, and they doso in a way that allows you to stack those modifications with each other.Given a class that implements such a queue, you could define traits to perform modifications such as these Doubling: double all integers that are put in the queue Incrementing: increment all integers that are put in the queue Filtering: filter out negative integers from a queue
  18. 18. Traits as stackable modificationsabstract class IntQueue {def get(): Intdef put(x: Int)}class BasicIntQueue extends IntQueue {private val buf = new ArrayBuffer[Int]def get() = buf.remove(0)def put(x: Int) { buf += x }}
  19. 19. Traits as stackable modificationsval queue = new BasicIntQueuequeue.put(10)queue.put(20)queue.get() it will return 10Queue.get() it will return 20
  20. 20. Traits as stackable modificationstake a look at using traits to modify this behaviortrait Doubling extends IntQueue {abstract override def put(x: Int) { super.put(2 * x) }}class MyQueue extends BasicIntQueue with Doublingval queue = new MyQueuequeue.put(10)queue.get() it will return 20
  21. 21. Traits as stackable modificationsStackable modification traits Incrementing and Filtering.trait Incrementing extends IntQueue {abstract override def put(x: Int) { super.put(x + 1) }}trait Filtering extends IntQueue {abstract override def put(x: Int) {if (x >= 0) super.put(x)}}
  22. 22. Traits as stackable modificationstake a look at using traits to modify this behaviorval queue = (new MyQueue extends BasicIntQueue with Doublingwith Incrementing with Filtering)queue.put(-1); queue.put(0); queue.put(1)queue.get()Int = 2 Filtering Increamenting Doubling
  23. 23. Option TypeScala has a standard type named Option for optionalvalues. Such a value can be of two forms. It can be of theform Some(x) where x is the actual value. Or it can bethe None object, which represents a missing value
  24. 24. Option Patternobject OptionPatternApp extends App { val result = divide(2, 0).getOrElse(0) println(result) def divide(x: Double, y: Double): Option[Double] = { try { Option(errorProneMethod(x, y)) } catch { case ex => None } } def errorProneMethod(x: Double, y: Double): Double = { if (y == 0) throw new Exception else {x / y} } }
  25. 25. Thanks