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
Ad

More Related Content

What's hot (18)

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
Scala
Sven Efftinge
 
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
 
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
 
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
 
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!
 
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
 

Similar to Inheritance And Traits (20)

Traits in scala
Traits in scalaTraits in scala
Traits in scala
Knoldus Inc.
 
Traits inscala
Traits inscalaTraits inscala
Traits inscala
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
 
classes-objects in oops java-201023154255.pptx
classes-objects in oops java-201023154255.pptxclasses-objects in oops java-201023154255.pptx
classes-objects in oops java-201023154255.pptx
janetvidyaanancys
 
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
 
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
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
classes-objects in oops java-201023154255.pptx
classes-objects in oops java-201023154255.pptxclasses-objects in oops java-201023154255.pptx
classes-objects in oops java-201023154255.pptx
janetvidyaanancys
 
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
 
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
 
Ad

Recently uploaded (20)

Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient CareAn Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
Cyntexa
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient CareAn Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
Cyntexa
 
Artificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptxArtificial_Intelligence_in_Everyday_Life.pptx
Artificial_Intelligence_in_Everyday_Life.pptx
03ANMOLCHAURASIYA
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Ad

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} } }
  翻译: