Traits inscala


Published on

The basic introduction of traits in scala.

Published in: Technology, Education
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Traits inscala

  2. 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. 3. SIMPLE EXAMPLE USING EXTENDtrait Example {def Test() {println("Hello World!")}}class Frog extends Example {}val frog = new Frogfrog.Test()
  4. 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. 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. 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. 7. Cont....val rect = new Rectangle(new Point(1, 1),newPoint(10,10))println(rect.width)Output: 9
  8. 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. 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. 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. 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. 12. Cont....For more example go to:
  13. 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. 14. References➢Programming in Scala, Martin Odersky➢A tour of Scala : Traits (see➢