Introduction to Scala Lecture 1 CMSC 331 SD Vick.

Slides:



Advertisements
Similar presentations
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Advertisements

OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Generic programming in Java
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 Gentle Introduction to Programming Session 5: Memory Model, Object Oriented Programming.
Programming in Scala Chapter 1. Scala: both object-oriented and functional Scala blends –object-oriented and –functional programming in a –statically.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
Introduction to Ruby CSE 413 Autumn 2008 Credit: Dan Grossman, CSE341.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
The Scala Programming Language
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
The Scala Programming Language presented by Donna Malayeri.
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.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Java Implementation: Part 3 Software Construction Lecture 8.
Effective Java: Generics Last Updated: Spring 2009.
Scala Overview Brandon Clopton CSCI 431. Scala fuses object-oriented and functional programming in a statically typed programming language. It is aimed.
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Multiparadigm Programming in Scala Adapted from presentation by H. C. Cunningham and J. C. Church University of Mississipi.
An Introduction to Python Blake Brogdon. What is Python?  Python is an interpreted, interactive, object-oriented programming language. (from python.org)
- 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.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
Recap form last time How to do for loops map, filter, reduce Next up: dictionaries.
Functions and Methods. Definitions and types A function is a piece of code that takes arguments and returns a result A pure function is a function whose.
Types in programming languages1 What are types, and why do we need them?
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
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.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
RUBY by Ryan Chase.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
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,
Duke CPS From C++ to Java l Java history: Oak, toaster-ovens, internet language, panacea l What it is ä O-O language, not a hybrid (cf. C++)
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
CSE 341 Section 10 Subtyping, Review, and The Future.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Sung-Dong Kim, Dept. of Computer Engineering, Hansung University Java - Introduction.
“Object-Oriented Meets Functional” SARAH BIRNBAUM KATHERINE JOYCE
Introduction to Scala SD Vick 1.
Java Primer 1: Types, Classes and Operators
Generics, Lambdas, Reflections
Java Programming Language
Building Java Programs
Generics, Lambdas, Reflections
Java Programming Language
Classes, Objects and Methods
Presentation transcript:

Introduction to Scala Lecture 1 CMSC 331 SD Vick

2 What’s Scala and why should You Care? It’s language written by by Martin Odersky at EPFLIt’s language written by by Martin Odersky at EPFL (École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland Influenced by ML/Haskell, Java and other languages with better support for component softwarewith better support for component software It’s a scalable Programming language for component software with a focus is on abstraction, composition, and decomposition and not on primitivesIt’s a scalable Programming language for component software with a focus is on abstraction, composition, and decomposition and not on primitives It unifies OOP and functional programmingIt unifies OOP and functional programming It interoperates with Java and.NETIt interoperates with Java and.NET

3 Why Scala? (Coming from Java/C++) Runs on the JVM –Can use any Java code in Scala –Almost as fast as Java (within 10%) Much shorter code –Odersky reports 50% reduction in most code over Java –Local type inference Fewer errors –No Null Pointer problems More flexibility –As many public classes per source file as you want –Operator overloading

4 Getting Started in Scala scala –Runs compiled scala code –Or without arguments, as an interpreter! scalac - compiles fsc - compiles faster! (uses a background server to minimize startup time) Go to scala-lang.org for downloads/documentation Read Scala: A Scalable Language (see language.html ) language.html

5 Features of Scala Scala is both functional and object-oriented –every value is an object –every function is a value--including methods Scala is statically typed –includes a local type inference system: –in Java 1.5: Pair p = new Pair (1, "Scala"); new Pair (1, "Scala"); – in Scala: val p = new MyPair(1, "scala");

6 Scala – The Interpreter Easiest way to get started with Scala is by using the Scala interpreter, which is an interactive “shell” for writing Scala expressions Simply type an expression into the interpreter and it will evaluate the expression and print the resulting value. $ scala This is an interpreter for Scala. Type in expressions to have them evaluated. Type :help for more information. scala> After you type an expression, such as 1 + 2, and hit return: scala> The interpreter will print: unnamed0: Int = 3 This line includes: an automatically assigned or user-defined name to refer to the computed value (unnamed0) a colon (:) the type of the expression and its resulting value (Int) an equals sign (=) the value resulting from evaluating the expression (3)

7 More features Supports lightweight syntax for anonymous functions, higher-order functions, nested functions, currying ML-style pattern matching Integration with XML –can write XML directly in Scala program –can convert XML DTD into Scala class definitions Support for regular expression patterns

8 Other features Allows defining new control structures without using macros, and while maintaining static typing Any function can be used as an infix or postfix operator Can define methods named +, <= or ::

9 Automatic Closure Construction Allows programmers to make their own control structures Can tag the parameters of methods with the modifier def. When method is called, the actual def parameters are not evaluated and a no- argument function is passed

10 object TargetTest1 with Application { def loopWhile(def cond: Boolean)(def body: Unit): Unit = if (cond) { body; loopWhile(cond)(body); } var i = 10; loopWhile (i > 0) { Console.println(i); i = i – 1 Note: var/val Note: var/val } While loop example Define loopWhile method Use it with nice syntax

Scala class hierarchy

12 Scala object system Class-based Single inheritance Can define singleton objects easily (no need for static which is not really OO) Traits, compound types, and views allow for more flexibility

13 Basic Scala Use var to declare variables: var x = 3; x += 4; Use val to declare values (final vars) val y = 3; y += 4; // error Notice no types, but it is statically typed var x = 3; x = “hello world”; // error Type annotations: var x : Int = 3;

14 Basic Scala Class instances val c = new IntCounter[String]; Accessing members (Look Ma no args!) println(c.size); // same as c.size() Defining functions: def foo(x : Int) { println(x == 42); } def bar(y : Int): Int = y + 42; // no braces // needed! def return42 = 42; // No parameters either!

15 Functions, Mapping, Filtering Defining lambdas – nameless functions (types sometimes needed) f is now a mapping int-> int val f = x :Int => x + 42; f is now a mapping int-> int A way to haul around stateClosures! A way to haul around state var y = 3; val g = {x : Int => y += 1; x+y; } Maps (and a cool way to do some functions) List(1,2,3).map(_+10).foreach(println) Filtering (and ranges!) 1 to 100 filter (_ % 7 == 3) foreach (println) –(Feels a bit like doing unix pipes?)

16 Classes and Objects trait Nat; object Zero extends Nat { def isZero: boolean = true; def pred: Nat = throw new Error("Zero.pred"); } class Succ(n: Nat) extends Nat { def isZero: boolean = false; def pred: Nat = n; }

17 Traits Similar to interfaces in Java They may have implementations of methods But can’t contain state Can be multiply inherited from

More on Traits Halfway between an interface and a class, called a trait. A class can incorporate as multiple Traits like Java interfaces but unlike interfaces they can also contain behavior, like classes. Also, like both classes and interfaces, traits can introduce new methods. Unlike either, the definition of that behavior isn't checked until the trait is actually incorporated as part of a class.

19 Example of traits trait Similarity { def isSimilar(x: Any): Boolean; def isNotSimilar(x: Any): Boolean = !isSimilar(x); } class Point(xc: Int, yc: Int) with Similarity { var x: Int = xc; var y: Int = yc; def isSimilar(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == x; }

20 Mixin class composition Basic inheritance model is single inheritance But mixin classes allow more flexibility class Point2D(xc: Int, yc: Int) { val x = xc; val y = yc; // methods for manipulating Point2Ds } class ColoredPoint2D(u: Int, v: Int, c: String) extends Point2D(u, v) { var color = c; def setColor(newCol: String): Unit = color = newCol; }

Mixin class composition example class Point3D(xc: Int, yc: Int, zc: Int) extends Point2D(xc, yc) { val z = zc; // code for manipulating Point3Ds } class ColoredPoint3D(xc: Int, yc: Int, zc: Int, col: String) extends Point3D(xc, yc, zc) with ColoredPoint2D(xc, yc, col); ColoredPoint2D Point2D Point3D ColoredPoint3D ColoredPoint2D

22 Mixin class composition Mixin composition adds members explicitly defined in ColoredPoint2D (members that weren’t inherited) Mixing a class C into another class D is legal only as long as D’s superclass is a subclass of C’s superclass. –i.e., D must inherit at least everything that C inherited Why?

23 Mixin class composition Remember that only members explicitly defined in ColoredPoint2D are mixin inherited So, if those members refer to definitions that were inherited from Point2D, they had better exist in ColoredPoint3D –They do, since ColoredPoint3D extends Point3D which extends Point2D

24 Views Defines a coercion from one type to another Similar to conversion operators in C++/C# trait Set { def include(x: int): Set; def include(x: int): Set; def contains(x: int): boolean def contains(x: int): boolean} def view(list: List) : Set = new Set { def include(x: int): Set = x prepend xs; def include(x: int): Set = x prepend xs; def contains(x: int): boolean = def contains(x: int): boolean = !isEmpty && (list.head == x || list.tail contains x) !isEmpty && (list.head == x || list.tail contains x)}

Views Views are inserted automatically by the Scala compiler If e is of type T then a view is applied to e if: –expected type of e is not T (or a supertype) –a member selected from e is not a member of T Compiler uses only views in scope Suppose xs : List and view above is in scope val s: Set = xs; xs contains x val s: Set =view(xs); val s: Set = view(xs); view(xs) contains x

26 Compound types motivation def cloneAndReset(obj: ?): Cloneable = { val cloned = obj.clone(); obj.reset; cloned } trait Resetable { def reset: Unit; } trait Cloneable { def clone(); }

27 Compound types In Java, the “solution” is: interface CloneableAndResetable extends Cloneable, Resetable But if the original object did not use the CloneableAndResetable interface, it won’t work Scala solution: use compound types (also called intersection types) def cloneAndReset(obj: Cloneable with Resetable): Cloneable = {... }

Variance annotations class Array[a] { def get(index: int): a def set(index: int, elem: a): unit; } Array[String] is not a subtype of Array[Any] If it were, we could do this: val x = new Array[String](1); val y : Array[Any] = x; y.set(0, new FooBar()); // just stored a FooBar in a String array!

29 Variance Annotations Covariance is ok with functional data structures trait GenList[+T] { def isEmpty: boolean; def head: T; def tail: GenList[T] } object Empty extends GenList[All] { def isEmpty: boolean = true; def head: All = throw new Error("Empty.head"); def tail: List[All] = throw new Error("Empty.tail"); } class Cons[+T](x: T, xs: GenList[T]) extends GenList[T] { def isEmpty: boolean = false; def head: T = x; def tail: GenList[T] = xs }

Variance Annotations Can also have contravariant type parameters –Useful for an object that can only be written to Scala checks that variance annotations are sound –covariant positions: immutable field types, method results –contravariant: method argument types –Type system ensures that covariant parameters are only used covariant positions (similar for contravariant)

Types as members abstract class AbsCell { type T; val init: T; private var value: T = init; def get: T = value; def set(x: T): unit = { value = x } } def createCell : AbsCell { new AbsCell { type T = int; val init = 1 } } Clients of createCell cannot rely on the fact that T is int, since this information is hidden from them

32 Resources The Scala programming language home page (see ) The Scala mailing list (see bin/doc_en?liste=scala ) bin/doc_en?liste=scala The Scala wiki (see ) A Scala plug-in for Eclipse (see lang.org/downloads/eclipse/index.html ) lang.org/downloads/eclipse/index.html A Scala plug-in for IntelliJ (see )

33 References The Scala Programming Language as presented by Donna Malayeri (see ) The Scala Language Specification 2.7 (seehttp:// ) The busy Java developer's guide to Scala: Of traits and behaviorsUsing Scala's version of Java interfaces(see scala04298.html ) scala04298.html First Steps to Scala (in Scalazine) by Bill Venners, Martin Odersky, and Lex Spoon, May 9, 2007 (see )