SlideShare uma empresa Scribd logo
1 de 15
TRAITS IN SCALA
JANMEJANI
SOFTWARE CONSULTANT
KNOLDUS SOFTWARE LLP
INTRODUCTION
➢
Traits in Scala are similar to interfaces, but much more powerful.
➢
A trait encapsulates method and field definitions, which can then be
reused by mixing them into classes.
➢
Unlike Java, Scala allows traits to be partially implemented; i.e. it is
possible to define default implementations for some methods.
➢
Once a trait is defined, it can be mixed in to a class using either the
“extends” or “with” keywords.
SIMPLE EXAMPLE USING EXTEND
trait Example {
def Test() {
println("Hello World!")
}
}
class Frog extends Example {
}
val frog = new Frog
frog.Test()
➢
If you wish to mix a trait into a class that explicitly extends a
superclass, you use “extends” to indicate the superclass and
“with” to mix in the trait.
class Animal
class Frog extends Animal with Example {
override def toString = "green"
}
class Animal
trait HasLegs
class Frog extends Animal with Example with HasLegs {
override def toString = "green"
}
Traits
Thin versus rich interfaces
➢
Rich has many methods (easier in theory for client)
Clients can pick a method that exactly matches the functionality the
need.
➢
Thin has fewer – easier for implementer
Clients calling into a thin interface, however, have to write more code.
Traits can be used to create Rich Interfaces which are Thin, means traits
can have lot of methods- Many of them are implemented in terms of the
few unimplemented methods. So the class which mixes these traits
provides the implementation for the few unimplemented methods.
For Example:
class Point(val x: Int, val y: Int)
class Rectangle(val topLeft: Point, val bottomRight:
Point) extends Rectangular {
}
trait Rectangular {
def topLeft: Point
def bottomRight: Point
def left = topLeft.x
def right = bottomRight.x
def width = right - left
}
Cont....
val rect = new Rectangle(new Point(1, 1),new
Point(10,10))
println(rect.width)
Output: 9
THE ORDERED TRAIT
➢
The Ordered trait in Scala is typically used when defining a class
of objects that know how to order themselves by comparing
against other instances of that class.
For Example:
case class Rational(n: Int, d: Int) extends Ordered[Rational] {
def compare(that: Rational) =
(this.n * that.d) - (that.n * this.d)
}
It should return zero if the objects are the same, negative if receiver is
less than the argument, and positive if the receiver is greater than the
argument.
TRAITS WITH STACKABLE
MODIFICATIONS
Stackable traits in Scala refers to being able to mix in multiple
traits that work together to apply multiple modifications to a
method.
How It Works:
In this pattern, a trait (or class) can play one of three roles:
➢
The base: defines an abstract interface
➢
A core or a stackable: implement the abstract methods and
provides functionality
For Example:
abstract class IntQueue {
def get(): Int
def put(x: Int)
}
Now we’ll build a concrete class
import scala.collection.mutable.ArrayBuffer
class BasicIntQueue extends IntQueue {
private val buf = new ArrayBuffer[Int]
def get() = buf.remove(0)
def put(x: Int) { buf += x }
}
TRAIT USEFUL FOR QUEUE
trait Doubling extends IntQueue {
abstract override def put(x: Int) { super.put(2 * x) }
}
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)
}
}
Cont....
For more example go to:
http://blog.knoldus.com/2012/11/27/scalaknol-understanding-traits-
TO TRAIT, OR NOT TO TRAIT?
➢
If the behavior will not be reused, then make it a concrete
class. It is not reusable behavior after all.
➢
If it might be reused in multiple, unrelated classes, make it a
trait. Only traits can be mixed into different parts of the class
hierarchy.
➢
If you want to inherit from it in Java code, use an abstract class.
Because a Scala trait with only abstract members translates directly to a
Java interface.
References
➢
Programming in Scala, Martin Odersky
➢
A tour of Scala : Traits (see
http://www.scala-lang.org/node/126)
➢
www.artima.com/scalazine/articles/stackable_trait_patte
rn.html
Traits in scala

Mais conteúdo relacionado

Mais procurados

Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectivegabalese
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
Scala基礎勉強会: Featherweight Scalaの紹介および型付け規則の決定可能性について
Scala基礎勉強会: Featherweight Scalaの紹介および型付け規則の決定可能性についてScala基礎勉強会: Featherweight Scalaの紹介および型付け規則の決定可能性について
Scala基礎勉強会: Featherweight Scalaの紹介および型付け規則の決定可能性についてHiroki Mizuno
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02Nguyen Tuan
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in ScalaKnoldus Inc.
 
Type Parameterization
Type ParameterizationType Parameterization
Type ParameterizationKnoldus Inc.
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useMukesh Tekwani
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 

Mais procurados (19)

Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspective
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
Scala基礎勉強会: Featherweight Scalaの紹介および型付け規則の決定可能性について
Scala基礎勉強会: Featherweight Scalaの紹介および型付け規則の決定可能性についてScala基礎勉強会: Featherweight Scalaの紹介および型付け規則の決定可能性について
Scala基礎勉強会: Featherweight Scalaの紹介および型付け規則の決定可能性について
 
Scala oo
Scala ooScala oo
Scala oo
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
 
Type Parameterization
Type ParameterizationType Parameterization
Type Parameterization
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
 
Google06
Google06Google06
Google06
 
Scala collections
Scala collectionsScala collections
Scala collections
 
C# programming
C# programming C# programming
C# programming
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 

Destaque

Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka RemotingKnoldus Inc.
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in ScalaKnoldus Inc.
 
Xml processing in scala
Xml processing in scalaXml processing in scala
Xml processing in scalaKnoldus Inc.
 
Intoduction on Playframework
Intoduction on PlayframeworkIntoduction on Playframework
Intoduction on PlayframeworkKnoldus Inc.
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parametersKnoldus Inc.
 
String Interpolation in Scala
String Interpolation in ScalaString Interpolation in Scala
String Interpolation in ScalaKnoldus Inc.
 
WorkingWithSlick2.1.0
WorkingWithSlick2.1.0WorkingWithSlick2.1.0
WorkingWithSlick2.1.0Knoldus Inc.
 
Akka vikas hazrati
Akka vikas hazratiAkka vikas hazrati
Akka vikas hazratiKnoldus Inc.
 
Modular programming Using Object in Scala
Modular programming Using Object in ScalaModular programming Using Object in Scala
Modular programming Using Object in ScalaKnoldus Inc.
 
FitNesse With Scala
FitNesse With ScalaFitNesse With Scala
FitNesse With ScalaKnoldus Inc.
 
Dependency injection in Scala
Dependency injection in ScalaDependency injection in Scala
Dependency injection in ScalaKnoldus Inc.
 
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Knoldus Inc.
 
Reactive programming with scala and akka
Reactive programming with scala and akkaReactive programming with scala and akka
Reactive programming with scala and akkaKnoldus Inc.
 

Destaque (19)

Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in Scala
 
Simple build tool
Simple build toolSimple build tool
Simple build tool
 
Xml processing in scala
Xml processing in scalaXml processing in scala
Xml processing in scala
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
Knolx session
Knolx sessionKnolx session
Knolx session
 
Intoduction on Playframework
Intoduction on PlayframeworkIntoduction on Playframework
Intoduction on Playframework
 
Intro lift
Intro liftIntro lift
Intro lift
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
String Interpolation in Scala
String Interpolation in ScalaString Interpolation in Scala
String Interpolation in Scala
 
WorkingWithSlick2.1.0
WorkingWithSlick2.1.0WorkingWithSlick2.1.0
WorkingWithSlick2.1.0
 
Akka vikas hazrati
Akka vikas hazratiAkka vikas hazrati
Akka vikas hazrati
 
Traits inscala
Traits inscalaTraits inscala
Traits inscala
 
Modular programming Using Object in Scala
Modular programming Using Object in ScalaModular programming Using Object in Scala
Modular programming Using Object in Scala
 
FitNesse With Scala
FitNesse With ScalaFitNesse With Scala
FitNesse With Scala
 
Dependency injection in Scala
Dependency injection in ScalaDependency injection in Scala
Dependency injection in Scala
 
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
 
Highcharts
HighchartsHighcharts
Highcharts
 
Reactive programming with scala and akka
Reactive programming with scala and akkaReactive programming with scala and akka
Reactive programming with scala and akka
 

Semelhante a Traits in scala

Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
IntroductiontoprogramminginscalaAmuhinda Hungai
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scalaehsoon
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosGenevaJUG
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanJimin Hsieh
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksSeniorDevOnly
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
Introduction to programming in scala
Introduction to programming in scalaIntroduction to programming in scala
Introduction to programming in scalaAmuhinda Hungai
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaDerek Chen-Becker
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture ThreeAngelo Corsaro
 

Semelhante a Traits in scala (20)

Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
scala.ppt
scala.pptscala.ppt
scala.ppt
 
Scala basic
Scala basicScala basic
Scala basic
 
Scala
ScalaScala
Scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Introduction to programming in scala
Introduction to programming in scalaIntroduction to programming in scala
Introduction to programming in scala
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture Three
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 

Mais de Knoldus Inc.

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxKnoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptxKnoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxKnoldus Inc.
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingKnoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesKnoldus Inc.
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxKnoldus Inc.
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 

Mais de Knoldus Inc. (20)

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 

Traits in scala

  • 1. TRAITS IN SCALA JANMEJANI SOFTWARE CONSULTANT KNOLDUS SOFTWARE LLP
  • 2. INTRODUCTION ➢ Traits in Scala are similar to interfaces, but much more powerful. ➢ A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. ➢ Unlike Java, Scala allows traits to be partially implemented; i.e. it is possible to define default implementations for some methods. ➢ Once a trait is defined, it can be mixed in to a class using either the “extends” or “with” keywords.
  • 3. SIMPLE EXAMPLE USING EXTEND trait Example { def Test() { println("Hello World!") } } class Frog extends Example { } val frog = new Frog frog.Test()
  • 4. ➢ If you wish to mix a trait into a class that explicitly extends a superclass, you use “extends” to indicate the superclass and “with” to mix in the trait. class Animal class Frog extends Animal with Example { override def toString = "green" } class Animal trait HasLegs class Frog extends Animal with Example with HasLegs { override def toString = "green" } Traits
  • 5. Thin versus rich interfaces ➢ Rich has many methods (easier in theory for client) Clients can pick a method that exactly matches the functionality the need. ➢ Thin has fewer – easier for implementer Clients calling into a thin interface, however, have to write more code. Traits can be used to create Rich Interfaces which are Thin, means traits can have lot of methods- Many of them are implemented in terms of the few unimplemented methods. So the class which mixes these traits provides the implementation for the few unimplemented methods.
  • 6. For Example: class Point(val x: Int, val y: Int) class Rectangle(val topLeft: Point, val bottomRight: Point) extends Rectangular { } trait Rectangular { def topLeft: Point def bottomRight: Point def left = topLeft.x def right = bottomRight.x def width = right - left }
  • 7. Cont.... val rect = new Rectangle(new Point(1, 1),new Point(10,10)) println(rect.width) Output: 9
  • 8. THE ORDERED TRAIT ➢ The Ordered trait in Scala is typically used when defining a class of objects that know how to order themselves by comparing against other instances of that class. For Example: case class Rational(n: Int, d: Int) extends Ordered[Rational] { def compare(that: Rational) = (this.n * that.d) - (that.n * this.d) } It should return zero if the objects are the same, negative if receiver is less than the argument, and positive if the receiver is greater than the argument.
  • 9. TRAITS WITH STACKABLE MODIFICATIONS Stackable traits in Scala refers to being able to mix in multiple traits that work together to apply multiple modifications to a method. How It Works: In this pattern, a trait (or class) can play one of three roles: ➢ The base: defines an abstract interface ➢ A core or a stackable: implement the abstract methods and provides functionality
  • 10. For Example: abstract class IntQueue { def get(): Int def put(x: Int) } Now we’ll build a concrete class import scala.collection.mutable.ArrayBuffer class BasicIntQueue extends IntQueue { private val buf = new ArrayBuffer[Int] def get() = buf.remove(0) def put(x: Int) { buf += x } }
  • 11. TRAIT USEFUL FOR QUEUE trait Doubling extends IntQueue { abstract override def put(x: Int) { super.put(2 * x) } } 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) } }
  • 12. Cont.... For more example go to: http://blog.knoldus.com/2012/11/27/scalaknol-understanding-traits-
  • 13. TO TRAIT, OR NOT TO TRAIT? ➢ If the behavior will not be reused, then make it a concrete class. It is not reusable behavior after all. ➢ If it might be reused in multiple, unrelated classes, make it a trait. Only traits can be mixed into different parts of the class hierarchy. ➢ If you want to inherit from it in Java code, use an abstract class. Because a Scala trait with only abstract members translates directly to a Java interface.
  • 14. References ➢ Programming in Scala, Martin Odersky ➢ A tour of Scala : Traits (see http://www.scala-lang.org/node/126) ➢ www.artima.com/scalazine/articles/stackable_trait_patte rn.html