SlideShare a Scribd company logo
Introducing Inheritance And Traits
             In Scala

              Piyush Mishra
            Software Consultant
           Knoldus Software LLP
Topics Covered

Inheritance

Traits

Mix-In Composition of traits into classes

Ordered Traits

Traits as Stackable modification

Option Pattern
Inheritance
Inheritance 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
                  extends
from a class.This is same as Java

class Animal
class Bird extends Animal

Omitting extends means extends AnyRef
Calling superclass constructor
Subclasses must immediately call their superclass constructor

 scala> class Animal(val name: String)
defined class Animal
scala> class Bird(name: String) extends Animal(name)
defined class Bird
Use the keyword final to prevent a
    class from being subclassed

Scala> final class Animal
defined class Animal

Scala> class Bird extends Animal
<console>:8: error: illegal inheritance from final class Animal
Use the keyword sealed to allow
       sub-classing only within the
            same source file
sealed class Animal

class Bird extends Animal

class Fish extends Animal

This means, that sealed classes can only be subclassed by you
but not by others, i.e. you know all subclasses
Use the keyword override to
      override a superclass member
class Animal {
val name = "Animal"
}
class Bird extends Animal {
override val name = "Bird"
}
Abstract classes
    Use the keyword abstract to define an abstract class

abstract class Animal {
val name: String
def hello: String
}
Implementing abstract members

Initialize or implement an abstract field or method to make it
                          Concrete

   class Bird(override val name: String) extends Animal {
                override def hello = "Beep"
                              }
Traits
   Traits are like Interfaces but they are richer than Java
                           Interfaces


They are fundamental unit of code reuse in Scala

 They encapsulates method and field definitions, which can
be reused by mixing them in classes

Unlike class inheritance a class can mix any number of traits

Unlike Interfaces they can have concrete methods
Unlike Java interfaces traits can
     explicitly inherit from a class

class A
trait B extends A
Mix-In Compotition
  One major use of traits is to automatically add methods to
class 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 already
extends another class

class Fish(val name: String) extends Animal with Swimmer

So method swim can mix into class Fish ,class Fish does not
need to implement it.
Mixing-in multiple traits

Use the keyword with repeatedly to mix-in multiple traits
Trait A
Trait B
Trait C
Class D extends A with B with C


If multiple traits define the same members, the outermost
                    (rightmost) one “wins”
Ordered Trait
 When-ever you compare two objects that are ordered, it is
convenient if you use a single method call to ask about the
precise 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 to
directly write things
 like “x <= y”.
Ordered Trait


We have a class Number


class Number(a:Int) {
val number =a
def < (that: Number) =this.number < that.number
def > (that: Number) = this.number > that.number
def <= (that: Number) = (this < that) || (this == that)
def >= (that: Number) = (this > that) || (this == that)
}
Ordered Trait

We have a class Number which extends ordered trait

class Number(a:Int) extends Ordered[Number] {
  val number=a
  def compare(that:Number)={this.number-that.number}
}
So compare method provide us all comparison
operators
Traits as stackable modifications
        Traits let you modify the methods of a class, and they do
so 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
Traits as stackable modifications
abstract class IntQueue {
def get(): Int
def put(x: Int)
}


class BasicIntQueue extends IntQueue {
private val buf = new ArrayBuffer[Int]
def get() = buf.remove(0)
def put(x: Int) { buf += x }
}
Traits as stackable modifications
val queue = new BasicIntQueue

queue.put(10)

queue.put(20)

queue.get() it will return 10

Queue.get() it will return 20
Traits as stackable modifications
take a look at using traits to modify this behavior

trait Doubling extends IntQueue {
abstract override def put(x: Int) { super.put(2 * x) }
}


class MyQueue extends BasicIntQueue with Doubling
val queue = new MyQueue

queue.put(10)
queue.get() it will return 20
Traits as stackable modifications

Stackable 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)
}
}
Traits as stackable modifications

take a look at using traits to modify this behavior

val queue = (new MyQueue extends BasicIntQueue with Doubling
with Incrementing with Filtering)

queue.put(-1); queue.put(0); queue.put(1)
queue.get()
Int = 2                                        Filtering
                                          Increamenting
                                              Doubling
Option Type

Scala has a standard type named Option for optional
values. Such a value can be of two forms. It can be of the
form Some(x) where x is the actual value. Or it can be
the None object, which represents a missing value
Option Pattern
object 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}
 }

                                     }
Thanks

More Related Content

What's hot

Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
manish kumar
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
Elizabeth alexander
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
Vasil Remeniuk
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
Vinod Kumar
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
maznabili
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Lovely Professional University
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
Edureka!
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Scala
ScalaScala
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
manish kumar
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java
yash jain
 
Lightning talk
Lightning talkLightning talk
Lightning talk
npalaniuk
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 

What's hot (18)

Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Inheritance in Java
Inheritance in JavaInheritance in Java
Inheritance in Java
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Scala
ScalaScala
Scala
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java
 
Lightning talk
Lightning talkLightning talk
Lightning talk
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 

Similar to Inheritance And Traits

Traits inscala
Traits inscalaTraits inscala
Traits inscala
Knoldus Inc.
 
Traits in scala
Traits in scalaTraits in scala
Traits in scala
Knoldus Inc.
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type Parameterization
Eelco Visser
 
scala.ppt
scala.pptscala.ppt
scala.ppt
Harissh16
 
Scala
ScalaScala
Scala
Zhiwen Guo
 
Scala idioms
Scala idiomsScala idioms
Scala idioms
Knoldus Inc.
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
DevaKumari Vijay
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
JayMistry91473
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
Arduino Aficionado
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
Madishetty Prathibha
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
Neelkanth Sachdeva
 
Scala oo
Scala ooScala oo
Scala oo
Knoldus Inc.
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 

Similar to Inheritance And Traits (20)

Traits inscala
Traits inscalaTraits inscala
Traits inscala
 
Traits in scala
Traits in scalaTraits in scala
Traits in scala
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type Parameterization
 
scala.ppt
scala.pptscala.ppt
scala.ppt
 
Scala
ScalaScala
Scala
 
Scala idioms
Scala idiomsScala idioms
Scala idioms
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Scala oo
Scala ooScala oo
Scala oo
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 

Recently uploaded

Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Zilliz
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 

Recently uploaded (20)

Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 

Inheritance And Traits

  • 1. Introducing Inheritance And Traits In Scala Piyush Mishra Software Consultant Knoldus Software LLP
  • 2. Topics Covered Inheritance Traits Mix-In Composition of traits into classes Ordered Traits Traits as Stackable modification Option Pattern
  • 3. Inheritance Inheritance 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 extends from a class.This is same as Java class Animal class Bird extends Animal Omitting extends means extends AnyRef
  • 4. Calling superclass constructor Subclasses must immediately call their superclass constructor scala> class Animal(val name: String) defined class Animal scala> class Bird(name: String) extends Animal(name) defined class Bird
  • 5. Use the keyword final to prevent a class from being subclassed Scala> final class Animal defined class Animal Scala> class Bird extends Animal <console>:8: error: illegal inheritance from final class Animal
  • 6. Use the keyword sealed to allow sub-classing only within the same source file sealed class Animal class Bird extends Animal class Fish extends Animal This means, that sealed classes can only be subclassed by you but not by others, i.e. you know all subclasses
  • 7. Use the keyword override to override a superclass member class Animal { val name = "Animal" } class Bird extends Animal { override val name = "Bird" }
  • 8. Abstract classes Use the keyword abstract to define an abstract class abstract class Animal { val name: String def hello: String }
  • 9. Implementing abstract members Initialize or implement an abstract field or method to make it Concrete class Bird(override val name: String) extends Animal { override def hello = "Beep" }
  • 10. Traits Traits are like Interfaces but they are richer than Java Interfaces They are fundamental unit of code reuse in Scala They encapsulates method and field definitions, which can be reused by mixing them in classes Unlike class inheritance a class can mix any number of traits Unlike Interfaces they can have concrete methods
  • 11. Unlike Java interfaces traits can explicitly inherit from a class class A trait B extends A
  • 12. Mix-In Compotition One major use of traits is to automatically add methods to class 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 already extends another class class Fish(val name: String) extends Animal with Swimmer So method swim can mix into class Fish ,class Fish does not need to implement it.
  • 13. Mixing-in multiple traits Use the keyword with repeatedly to mix-in multiple traits Trait A Trait B Trait C Class D extends A with B with C If multiple traits define the same members, the outermost (rightmost) one “wins”
  • 14. Ordered Trait When-ever you compare two objects that are ordered, it is convenient if you use a single method call to ask about the precise 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 to directly write things like “x <= y”.
  • 15. Ordered Trait We have a class Number class Number(a:Int) { val number =a def < (that: Number) =this.number < that.number def > (that: Number) = this.number > that.number def <= (that: Number) = (this < that) || (this == that) def >= (that: Number) = (this > that) || (this == that) }
  • 16. Ordered Trait We have a class Number which extends ordered trait class Number(a:Int) extends Ordered[Number] { val number=a def compare(that:Number)={this.number-that.number} } So compare method provide us all comparison operators
  • 17. Traits as stackable modifications Traits let you modify the methods of a class, and they do so 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. Traits as stackable modifications abstract class IntQueue { def get(): Int def 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. Traits as stackable modifications val queue = new BasicIntQueue queue.put(10) queue.put(20) queue.get() it will return 10 Queue.get() it will return 20
  • 20. Traits as stackable modifications take a look at using traits to modify this behavior trait Doubling extends IntQueue { abstract override def put(x: Int) { super.put(2 * x) } } class MyQueue extends BasicIntQueue with Doubling val queue = new MyQueue queue.put(10) queue.get() it will return 20
  • 21. Traits as stackable modifications Stackable 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. Traits as stackable modifications take a look at using traits to modify this behavior val queue = (new MyQueue extends BasicIntQueue with Doubling with Incrementing with Filtering) queue.put(-1); queue.put(0); queue.put(1) queue.get() Int = 2 Filtering Increamenting Doubling
  • 23. Option Type Scala has a standard type named Option for optional values. Such a value can be of two forms. It can be of the form Some(x) where x is the actual value. Or it can be the None object, which represents a missing value
  • 24. Option Pattern object 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} } }