Scala
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

Scala

  • 751 views
Uploaded on

Presentation based on Martin Odersky's presentation at FOSDEM 2009 and adapted for the SE490 TA lecture

Presentation based on Martin Odersky's presentation at FOSDEM 2009 and adapted for the SE490 TA lecture

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
751
On Slideshare
751
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
6
Comments
0
Likes
1

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. The Scala Programming Language SE 464 Leonardo Passos (lpassos@gsd.uwaterloo.ca)
  • 2. Introduction
  • 3. Scala● Scala = Scalable Language● Created in 2001, at EPFL, Switzerland “Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It smoothly integrates features of object-oriented and functional languages. It is also fully interoperable with Java.” From http://www.scala-lang.org/node/273
  • 4. Scala vs Java● Java public class PrintOptionsJava { public static void main(String[] args) { for(String arg : args) { if (arg.startsWith("-")) System.out.println(arg.substring(1)); } } }● Scala object PrintOptionsScala { def main(args:Array[String]) { for (arg <- args if arg startsWith "-") println(arg.substring(1)) } }
  • 5. Scala vs Java● Scala method ● Java method def fun(x:Int) : Int = { int fun(int x) { result return result ; } } def fun = result (No parameter-less methods)● Scala variables ● Java variables var x:Int = expression int x = expression var x = expression val x:Int = expression final int x = expression
  • 6. Scala vs Java● Scala method calls ● Java method calls obj.meth(arg) obj.meth(args) obj meth arg (no infix notation)● Scala choice expressions ● Java choice expressions if (cond) exp1 else exp2 (cond) ? exp1 : exp2 expr match { switch(expr) { pattern1 => exp1 case int-literal1: exp1 pattern2 => exp2 break ; … case int-literal2: exp2 pattern-n => exp-n break ; } … case int-literal-n: exp-n ; More on patterns to come... }
  • 7. Scala vs Java● Scala traits ● Java interfaces trait T { interface T { def abstractMethod(x:Int) : Int int abstractMethod(int x) ; def concreteMethod(x:Int) = f + field } var field = 33 } No concrete methods Nor fields● Scala mixin composition ● Java extension + impl. class Sub extends Super with T class Sub extends Super implements T
  • 8. Scala vs Java● Scala class and object ● Java class w/ static class Sample { class Sample(x:Int) { def instanceMethod(y:Int) = x + y private int x ; } public Sample(int x) { object Sample { this.x = x ; def staticMethod(x:Int, y:Int) = x * y } } public int instanceMethod(int y) { return x + y ; } public static int staticMethod(int x, int y) { return x * y ; } }
  • 9. Scala vs Java● Equality comparison ● a == b is the same as a.equals(b) in Java ● a.eq(b) is the same as a == b in Java● Import statements ● _ instead of * in Java ● Example: import scala.math._
  • 10. Scala vs Java● Scala is concise ● Average reduction in LOC: ≥ 2 object QuickSort { def apply[T](list : List[T])(implicit ordering : Ordering[T]) : List[T] = { import ordering._ list match { case Nil => List() case (x::xs) => apply(for(n <- xs if n <= x) yield n) ++ List(x) ++ apply(for(n <- xs if n > x) yield n) } } } object Main { def main(args:Array[String]) = QuickSort(List(4,3,2,1)) foreach println }
  • 11. Scala is a Purely OO Language!● Every value is an object● Every operation (including +, *, /, etc) is a message send ● 1 + 2 * 3 is actually 1.+(2.*(3)) ● Operator symbols are valid identifiers ● Every identifier between two expressions is taken to be an operation (method call) – infix notation
  • 12. Extracted from [1].
  • 13. Functions are Objects● The snippet def main(args:Array[String]) = QuickSort(List(4,3,2,1)) foreach println means def main(args:Array[String]) = QuickSort(List(4,3,2,1)).foreach(x => println(x)) Function (anonymous) passed as parameter foreach is a high order function
  • 14. Functions are Objects● Method to inspect whether there exists a row in a matrix containing only zeros: def hasZeroRow(matrix:Array[Array[Int]]) = matrix exists (row => row forall (0 == )) ● How many functions are being passed as parameters? ● What does (0 == ) mean?
  • 15. Scala is Extensible ● Scala does not have break/continue in the language. But...package scala.util.control import scala.util.control.Breaks._object Breaks { breakable { private class BreakException extends RuntimeException for(x <- elems) { private val breakException = new BreakException println(x * 2) if (x > 0) def break = throw breakException break } def breakable(op: => Unit) { } try { op } catch { case _ : BreakException => /* Do nothing. */ } }}
  • 16. Classes
  • 17. Classes● Scala classes: abstract or concrete● Modifiers ● Case: allows pattern matching ● Sealed: prevents further inheritance (= Java final classes)● Parameters: ● Values: defines the class primary constructor ● Types: allow generic classes
  • 18. Classes ● A hierarchy of Boolean expressionspackage bcalculatorabstract class Expabstract class BinaryExp(val left:Exp, val right:Exp) extends Expcase class OrExp(override val left:Exp, override val right:Exp) extends BinaryExp(left, right)case class AndExp(override val left:Exp, override val right:Exp) extends BinaryExp(left, right)case class BooleanLiteralExp(val value:Boolean) extends Exp ● Note: instances of case classes do not require new
  • 19. Classes● Generic classes class Stack[T] { var elems: List[T] = Nil def push(x: T) { elems = x :: elems } def top: T = elems.head def pop() { elems = elems.tail } }● Stack, as defined, has no-variance. ● Stack[Book] ≰ Stack[Thing] ● Stack[Thing] ≰ Stack[Book]
  • 20. Classes● Covariance package scala.collection.immutable sealed abstract class Stack[+A] extends ...● Therefore: ● Stack[Book] ≤ Stack[Thing]
  • 21. Classes● Contravariance class Output[-A] {def write(a : A) = { /*do write*/ } } object OutputWriter { def writeObject(out : Output[Object]) = out.write("hello") def main(args:Array[String]) { writeObject(new Output[Any]) } }● Therefore: ● Output[Any] ≤ Output[Object] (note that Object ≤ Any)
  • 22. Pattern Matching
  • 23. Pattern Matching● Applicable only to case classes.● Checks the type and verifies whether the object matches an instance pattern: object Calculator { def eval(exp:Exp) : Boolean = { exp match { case BooleanLiteralExp(v) => v case OrExp(left, right) => eval(left) || eval(right) case AndExp(left, right) => eval(left) && eval(right) } } }
  • 24. Pattern Matching● When doing matching, the pattern follows the structure of the target class primary constructor● If parts of the pattern are themselves instances of case classes, you can further nest them case OrExp(left, BooleanLiteralExp(false)) => eval(left) case OrExp(BooleanLiteralExp(false), right) => eval(right) case OrExp(BooleanLiteralExp(true), _) => true case OrExp(_, BooleanLiteralExp(true)) => true● Other structures different from the primary constructor can be explored using extractors
  • 25. Traits
  • 26. Traits● Similar to Java interfaces● May contain variables and implementation● Contrary to classes, traits have no constructor● Cannot be instantiated, even if fully specified● Can be generic and inherit from other traits
  • 27. abstract class AbsIterator { type T def hasNext: Boolean def next: T}trait RichIterator extends AbsIterator { def foreach(f: T => Unit) { while (hasNext) f(next) }}class StringIterator(s: String) extends AbsIterator { type T = Char private var i = 0 def hasNext = i < s.length() def next = { val ch = s charAt i; i += 1; ch }}object StringIteratorTest { def main(args: Array[String]) { class Iter extends StringIterator(args(0)) with RichIterator val iter = new Iter iter foreach println }}
  • 28. Questions?
  • 29. References1. An Overview of the Scala Programming Language www.scala-lang.org/docu/files/ScalaOverview.pdf2. Scala by Example http://www.scala-lang.org/docu/files/ScalaByExample.pdf3. Programming in Scala – A comprehensive step by step guide (book by Artima).4. Programming Scala (book by OReilly)