SlideShare a Scribd company logo
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

More Related Content

PDF
TI1220 Lecture 8: Traits & Type Parameterization
ODP
Introducing scala
PDF
Scala categorytheory
PDF
Getting Started With Scala
PDF
Inheritance And Traits
PDF
Getting Started With Scala
PPTX
Scala Back to Basics: Type Classes
PDF
Suit case class
TI1220 Lecture 8: Traits & Type Parameterization
Introducing scala
Scala categorytheory
Getting Started With Scala
Inheritance And Traits
Getting Started With Scala
Scala Back to Basics: Type Classes
Suit case class

What's hot (19)

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

Viewers also liked (19)

PDF
Akka Futures and Akka Remoting
ODP
Functions & Closures in Scala
PPT
Simple build tool
ODP
Xml processing in scala
ODP
Slickdemo
ODP
Knolx session
PPT
Intoduction on Playframework
PPT
Intro lift
PDF
Implicit conversion and parameters
ODP
String Interpolation in Scala
ODP
WorkingWithSlick2.1.0
PDF
Akka vikas hazrati
PPT
Traits inscala
ODP
Modular programming Using Object in Scala
PDF
FitNesse With Scala
ODP
Dependency injection in Scala
ODP
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
ODP
Highcharts
ODP
Reactive programming with scala and akka
Akka Futures and Akka Remoting
Functions & Closures in Scala
Simple build tool
Xml processing in scala
Slickdemo
Knolx session
Intoduction on Playframework
Intro lift
Implicit conversion and parameters
String Interpolation in Scala
WorkingWithSlick2.1.0
Akka vikas hazrati
Traits inscala
Modular programming Using Object in Scala
FitNesse With Scala
Dependency injection in Scala
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Highcharts
Reactive programming with scala and akka
Ad

Similar to Traits in scala (20)

PPT
Scala Talk at FOSDEM 2009
PPT
scala.ppt
PPTX
Scala basic
PPT
Scala
PDF
Getting Started With Scala
PDF
Introductiontoprogramminginscala
ODP
Functional programming with Scala
PDF
The Scala Programming Language
PPTX
Principles of functional progrmming in scala
PDF
Scala at GenevaJUG by Iulian Dragos
PDF
Introduction to Scala for JCConf Taiwan
PDF
Lecture 3
PDF
From Java to Scala - advantages and possible risks
PPTX
Intro to Scala
PPT
Scala - brief intro
ODP
Functional Programming With Scala
PDF
Introduction to programming in scala
PDF
Stepping Up : A Brief Intro to Scala
PDF
Programming in Scala - Lecture Three
PPT
An introduction to scala
Scala Talk at FOSDEM 2009
scala.ppt
Scala basic
Scala
Getting Started With Scala
Introductiontoprogramminginscala
Functional programming with Scala
The Scala Programming Language
Principles of functional progrmming in scala
Scala at GenevaJUG by Iulian Dragos
Introduction to Scala for JCConf Taiwan
Lecture 3
From Java to Scala - advantages and possible risks
Intro to Scala
Scala - brief intro
Functional Programming With Scala
Introduction to programming in scala
Stepping Up : A Brief Intro to Scala
Programming in Scala - Lecture Three
An introduction to scala

More from Knoldus Inc. (20)

PPTX
Angular Hydration Presentation (FrontEnd)
PPTX
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
PPTX
Self-Healing Test Automation Framework - Healenium
PPTX
Kanban Metrics Presentation (Project Management)
PPTX
Java 17 features and implementation.pptx
PPTX
Chaos Mesh Introducing Chaos in Kubernetes
PPTX
GraalVM - A Step Ahead of JVM Presentation
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
DAPR - Distributed Application Runtime Presentation
PPTX
Introduction to Azure Virtual WAN Presentation
PPTX
Introduction to Argo Rollouts Presentation
PPTX
Intro to Azure Container App Presentation
PPTX
Insights Unveiled Test Reporting and Observability Excellence
PPTX
Introduction to Splunk Presentation (DevOps)
PPTX
Code Camp - Data Profiling and Quality Analysis Framework
PPTX
AWS: Messaging Services in AWS Presentation
PPTX
Amazon Cognito: A Primer on Authentication and Authorization
PPTX
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
PPTX
Managing State & HTTP Requests In Ionic.
Angular Hydration Presentation (FrontEnd)
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Self-Healing Test Automation Framework - Healenium
Kanban Metrics Presentation (Project Management)
Java 17 features and implementation.pptx
Chaos Mesh Introducing Chaos in Kubernetes
GraalVM - A Step Ahead of JVM Presentation
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
DAPR - Distributed Application Runtime Presentation
Introduction to Azure Virtual WAN Presentation
Introduction to Argo Rollouts Presentation
Intro to Azure Container App Presentation
Insights Unveiled Test Reporting and Observability Excellence
Introduction to Splunk Presentation (DevOps)
Code Camp - Data Profiling and Quality Analysis Framework
AWS: Messaging Services in AWS Presentation
Amazon Cognito: A Primer on Authentication and Authorization
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Managing State & HTTP Requests In Ionic.

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