Your SlideShare is downloading. ×
Traits inscala
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

Traits inscala

148
views

Published on


0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
148
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
1
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. TRAITS IN SCALAJANMEJANISOFTWARE CONSULTANTKNOLDUS 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 bereused by mixing them into classes.➢Unlike Java, Scala allows traits to be partially implemented; i.e. it ispossible 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 EXTENDtrait Example {def Test() {println("Hello World!")}}class Frog extends Example {}val frog = new Frogfrog.Test()
  • 4. ➢If you wish to mix a trait into a class that explicitly extends asuperclass, you use “extends” to indicate the superclass and“with” to mix in the trait.class Animalclass Frog extends Animal with Example {override def toString = "green"}class Animaltrait HasLegsclass 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 theneed.➢Thin has fewer – easier for implementerClients calling into a thin interface, however, have to write more code.Traits can be used to create Rich Interfaces which are Thin, means traitscan have lot of methods- Many of them are implemented in terms of thefew unimplemented methods. So the class which mixes these traitsprovides 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: Pointdef bottomRight: Pointdef left = topLeft.xdef right = bottomRight.xdef width = right - left}
  • 7. Cont....val rect = new Rectangle(new Point(1, 1),newPoint(10,10))println(rect.width)Output: 9
  • 8. THE ORDERED TRAIT➢The Ordered trait in Scala is typically used when defining a classof objects that know how to order themselves by comparingagainst 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 isless than the argument, and positive if the receiver is greater than theargument.
  • 9. TRAITS WITH STACKABLEMODIFICATIONSStackable traits in Scala refers to being able to mix in multipletraits that work together to apply multiple modifications to amethod.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 andprovides functionality
  • 10. For Example:abstract class IntQueue {def get(): Intdef put(x: Int)}Now we’ll build a concrete classimport scala.collection.mutable.ArrayBufferclass BasicIntQueue extends IntQueue {private val buf = new ArrayBuffer[Int]def get() = buf.remove(0)def put(x: Int) { buf += x }}
  • 11. TRAIT USEFUL FOR QUEUEtrait 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 concreteclass. It is not reusable behavior after all.➢If it might be reused in multiple, unrelated classes, make it atrait. Only traits can be mixed into different parts of the classhierarchy.➢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 aJava interface.
  • 14. References➢Programming in Scala, Martin Odersky➢A tour of Scala : Traits (seehttp://www.scala-lang.org/node/126)➢www.artima.com/scalazine/articles/stackable_trait_pattern.html