SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip 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 BORSANIYAMaulik 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_keywordsmanish kumar
 
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 pptVinod Kumar
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objectsmaznabili
 
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 | EdurekaEdureka!
 
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 conceptmanish kumar
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritancemanish kumar
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java yash jain
 
Lightning talk
Lightning talkLightning talk
Lightning talknpalaniuk
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 

Tendances (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
 

Similaire à INTRODUCING INHERITANCE AND 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 ParameterizationEelco Visser
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scalaehsoon
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 

Similaire à INTRODUCING INHERITANCE AND TRAITS IN SCALA (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
 

Dernier

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 

Dernier (20)

New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 

INTRODUCING INHERITANCE AND TRAITS IN SCALA

  • 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} } }