UMBC CMSC 331 Traits in Scala. 2 Basic Properties Traits are used to define object types by specifying the signature of the supported methods. Unlike.

Slides:



Advertisements
Similar presentations
Generics, Lists, Interfaces
Advertisements

Interfaces.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
OBJECT-ORIENTED PROGRAMMING. What is an “object”? Abstract entity that contains data and actions Attributes (characteristics) and methods (functions)
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Inheritance, Shared. Projectiles Program Demonstrates – Inheritance – MustInherit – Shared vs. Non-shared methods A variation on the Multiball example.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Scala Actors -Terrance Dsilva.  Thankfully, Scala offers a reasonable, flexible approach to concurrency  Actors aren’t a concept unique to Scala.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
The Scala Programming Language presented by Donna Malayeri.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Predefined Classes in Java Ellen Walker CPSC 201 Data Structures Hiram College.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Introduction to Scala Lecture 1 CMSC 331 SD Vick.
More about Classes and Objects. Names Scala has three kinds of names for variables and methods Names composed of letters, underscores, and dollar signs.
- Neeraj Chandra.  It’s language written by by Martin Odersky at EPFL  It’s language written by by Martin Odersky at EPFL (École Polytechnique Fédérale.
1 Cisco Unified Application Environment Developers Conference 2008© 2008 Cisco Systems, Inc. All rights reserved.Cisco Public Introduction to Etch Scott.
Inheritance Building one object from another. Background Object-oriented programming is normally described has offering three capabilities Encapsulation:
These materials where developed by Martin Schray. Please feel free to use and modify them for non-commercial purposes. If you find them useful or would.
AP Computer Science A – Healdsburg High School 1 Interfaces, Abstract Classes and the DanceStudio - Similarities and Differences between Abstact Classes.
1 Programming in Scala – Mixin inheritance Summer 2008.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
The Scala API. Scala has a reputation of being a difficult language Some people feel that Scala is beyond what the average programmer can master Others.
Inheritance and Access Control CS 162 (Summer 2009)
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,
Classes, Interfaces and Packages
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
21. PHP Classes To define a class, use the keyword class followed by the name and a block with the properties and method definitions Properties are declared.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Object Oriented Programming in Java Habib Rostami Lecture 7.
This In Java, the keyword this allows an object to refer to itself. Or, in other words, this refers to the current object – the object whose method or.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
UMBC CMSC 331 Case Classes in Scala Intro. Basic Properties Case classes are regular classes which export their constructor parameters and which provide.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Web Design & Development Lecture 9
Lecture 12 Inheritance.
Agenda Warmup AP Exam Review: Litvin A2
University of Central Florida COP 3330 Object Oriented Programming
Generics, Lambdas, Reflections
Class vs Abstract vs Interface
EE 422C Java Reflection re·flec·tion rəˈflekSH(ə)n/ noun
null, true, and false are also reserved.
Interfaces.
Case Classes in Scala Intro
Barb Ericson Georgia Institute of Technology Oct 2005
Java Inheritance.
Object-Oriented Programming
The Scala API.
Chapter 8 Class Inheritance and Interfaces
Jim Fawcett CSE687 – Object Oriented Design Spring 2014
Inheritance Lakshmish Ramaswamy.
C++ Object Oriented 1.
Presentation transcript:

UMBC CMSC 331 Traits in Scala

2 Basic Properties Traits are used to define object types by specifying the signature of the supported methods. Unlike Java, Scala allows traits to be partially implemented; i.e. it is possible to define default implementations for some methods. Traits may not have constructors 2

3 Simple Example Using Extends 3 trait Similarity { def isSimilar(x: Any): Boolean def isNotSimilar(x: Any): Boolean = !isSimilar(x) } This trait consists of two methods isSimilar and isNotSimilar  isSimilar is abstract  isNotSimilar is concrete but written in terms of isSimilar Classes that integrate this trait only have to provide a concrete implementation forisSimilar, isNotSimilar gets inherited directly from the trait

4 What’s the output? (Part 1) 4 class Point(xc: Int, yc: Int) extends Similarity { var x: Int = xc var y: Int = yc def isSimilar(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == x }

5 What’s the output? (Part 2) 5 object TraitsTest extends Application { val p1 = new Point(2, 3) val p2 = new Point(2, 4) val p3 = new Point(3, 3) println(p1.isNotSimilar(p2)) println(p1.isNotSimilar(p3)) println(p1.isNotSimilar(2)) }

6 Mixing in a Trait Using With 6 Consider the running example on pgs of Odersky Since Philosophical and HasLegs are Traits and Animal is a class we may write: class Frog extends Animal with Philosophical with HasLegs { override def toString = “green” override def philosophize =println(“Itain’t easy being “+ toString +”!”) }

7 The Ordered Trait 7 Thin vs. Rich Interfaces  Rich has many methods (easier in theory for client)  Thin has fewer – easier for implementer (see Odersky) The Ordered Trait If Interface is rich then must supply, = instead want a trait with a single method (here is an example) class Rational (n : Int, d : Int) extends Ordered[Rational] { def compare (that: Ratioonal) = (this.numer * that.denom)– (that.numer * this.denom) }

8 Traits with Stackable Modifications 8 Use to stack modifications to a class Consider the IntQueue class from Odersky (pg 223) abstract class IntQueue { def get () : Int def put(x : Int) } Now we’ll build a concrete class atop of it

9 An implementation 9 import scala.collection.mutable.ArrayBuffer class BasicQueue extends IntQueue{ private val buf = new ArrayBuffer[int] def get () : buf.remove(0) def put(x : Int) { buf += x } }

10 A Trait Useful For the Queue 10 trait Doubling extends IntQueue { abstract override def put (x : Int) { super.put(2*x) } } Can only be used with IntQueues This refers to the class that actually uses the trait val queue = new BasicIntQueue with Doubling queue.put(10) queue.get()

11 Two Additional Traits 11 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 trait Similar{ def isSimilar(x: Any): Boolean def isNotSimilar(x: Any): Boolean = !isSimilar(x) } case class MyInt (x :Int) extends Similar { def isSimilar(x :Int) : Boolean = m.isInstance[MyInt] && m.asInstanceOf[MyInt].x = x } trait Similar{ def isSimilar(x: Any): Boolean def isNotSimilar(x: Any): Boolean = !isSimilar(x) } case class MyInt (x :Int) extends Similar { def isSimilar(x :Int) : Boolean = m.isInstance[MyInt] && m.asInstanceOf[MyInt].x = x } Upper Bounds(1) 12

13 Upper Bounds(2) 13

14 case class ChangeEvent[OnType](on: OnType) trait Observer[T] { this: T with Observer[T] => type ChangeHandler = { def changed(c: ChangeEvent[T with Observer[T]]): Unit } private var observers: List[ChangeHandler] = Nil def addObserver(c: ChangeHandler) = synchronized { observers = c :: observers } … } Involved Example Using Traits 14 The param is the type of thing that changed this this The type of thing for this in the trait is just the type of the thing we’ve mixed Observer into. We don’t know T till runtime. Using this as shown is called a self type – see Odersky pg 537 A type that matched anything with that method and signature

15 Rest of Trait Definition 15 trait Observer[T] { … def removeObserver(c: ChangeHandler)= synchronized { observers -= c } protected def updateObservers() = synchronized { val ch = ChangeEvent(this) Observers.foreach(i =>i.changed(ch)) } A ChangeEvent has been made ( a case class), tell each observer about the change.

16 class Shibby extends Observer[Shibby] { private var _count = 0 def count = synchronized{_count} def inc = synchronized { _count += 1 updateObservers() } val s = new Shibby Testing 16 This class generates the events and then tells the Observers about it

17 Testing 17 object Dibby { def changed(c: ChangeEvent[Shibby]) { println(“Dibby changed: + c.on.count)} } object Doo{ def changed(c: ChangeEvent[Shibby]) { println(“Doo changed: + c.on.count)} } These classes respond to the changes

18 Observer Get Events 18 s.addObserver(Dibby) s.addObserver(Doo) s.inc Dibby changed 1 Doo changed 1 s.removeObserver(Dibby) s.inc Doo changed 2

19 References 19 A tour of Scala : Traits (see lang.org/node/126) lang.org/node/126 Programming in Scala, Martin Odersky et al, Artima press 2009 Beginning Scala, David Pollak, Apress, 2009