introduction to scala

32
Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion Introduction to Scala The “new” Java? Eivind Barstad Waaler BEKK/UiO July 4, 2009 Eivind Barstad Waaler BEKK/UiO Introduction to Scala

Upload: eivindw

Post on 15-Nov-2014

25 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Introduction to ScalaThe “new” Java?

Eivind Barstad Waaler

BEKK/UiO

July 4, 2009

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 2: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Presentation Outline

Outline

Introduction

Concise Syntax

Object Orientation

Functional Programming

Various Stuff

Conclusion

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 3: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Introducing Scala

What is Scala?

I 100% Object-oriented

I Functional programming

I Typing: static, strong, inferred/implicitsI Java bytecode → JVM

I .NET (CLR) Also available

I Extensibility

I Java-like syntax → Scala syntax

I Current version 2.7.5 → 2.8

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 4: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Introducing Scala

A first example

class IntMath(val x: Int, val y: Int) {

def sum(): Int = {x + y;

}

def mul = x * y}

val test = new IntMath(3, 4)

println(test.x) // output: 3println(test.sum) // output: 7println(test.mul()) // output: 12

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 5: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Introducing Scala

The Scala Interpreter

I An interactive “shell” for writing Scala expressions

I Automatically creates temporary result variables

I Simply type ’scala’ at the command promptI Using Maven2:

I Type ’mvn scala:console’I Starts the Scala Interpreter with project classpath

I Demo ⇒

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 6: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Syntax Examples

Imports

I Like Java, but more features

I Can be anywhere

I Import from packages, classes or objects

import java.util._ // Allimport java.util.{ArrayList,HashSet} // Selectedimport java.util.{ArrayList => _, _} // All exceptimport java.util.ArrayList._ // All from AL

val list = new ArrayListimport list._ // All from object list

import java.sql.{Date => SDate} // Renamingimport java.util.Date

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 7: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Syntax Examples

Method syntax

I . and () can be omitted for binary/unary methods

I Methods can have any name

I Operators are simply methods → full operator overloading

2.max(5) // max of 2 and 52 max 5 // same as above

class MyNumber(val num: Int) {def +(other: MyNumber) = new MyNumber(other.num + num)

}val x = new MyNumber(5)val y = new MyNumber(6)val z = x + y

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 8: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Syntax Examples

Type inferrence/implicits

I If type is obvious – no need to write it

I Implicits can be defined

I Implicits heavily used in std lib (RichInt etc.)

// Type inferrenceval a = 42 // Type = Intval b = "hello world!" // Type = Stringdef add(x: Int, y: Int) = x + y // Return-type = Intval sum = add(3, 5) // Type of sum = Int

// Implicitsclass MyInt(val i: Int) { def doubleIt = i * 2 }implicit def fromInt(i: Int) = new MyInt(i)5.doubleIt // = 10

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 9: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

OO Introduction

Object Orientation

I Pure OO – everything is an object

I Classes – blueprints for objects (like Java)

I Singleton objects

I Traits – AOP like possibilities

I Semicolon inference

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 10: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Classes and Objects

Scala Class Hierarchy

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 11: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Classes and Objects

ClassesI Much like JavaI Contains fields and methods – can override eachother

I override keyword mandatoryI Can take parameters directly – constructor

class A(val num: Int)class B(num: Int, val str: String) extends A(num) {def calc() = num * num // calc is a method

}class C(num: Int, str: String) extends B(num, str) {override val calc = 65 // override method with val

}

val a = new A(35) // Type Aval b = new B(32, "Eivind") // Type B - calc methodval b2: B = new C(32, "Eivind") // Also type B - calc val

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 12: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Classes and Objects

Singleton ObjectsI No static members in Scala → Singleton ObjectsI Keyword object instead of classI Companion class/object – same name

I Factory methodsI Other unique/static behaviour

// Array class definitionfinal class Array[A](_length: Int) extends Array0[A]

// Array object definition with methodobject Array {def apply(xs: Int*): Array[Int] = { ... }

}

// Create array with four integersval arr = Array(1, 2, 3, 4)

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 13: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Classes and Objects

The “magic” apply()-methodI Scala provides special syntax for calling the apply() methodI In classes used to look up elements (for instance in

Collections)I In objects used to create class instancesI Functions in Scala are actually just apply() methodsI Make your classes/objects appear as built-in syntax

// Array object has apply method for creating arraysdef apply(xs: Int*): Array[Int] = { ... }// Array class has apply method to access the arraydef apply(i: Int): A

// Scala special syntaxval arr = Array(4, 3, 2, 1) // Array.apply(4, 3, 2, 1)val three = arr(1) // arr.apply(1)

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 14: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Traits

TraitsI Encapsulates method and field definitions, much like classesI A class can mix in any number of traits → multiple inheritanceI Widen thin interfaces to rich onesI Define stackable modifications

trait Hello {def hello { println("Hello!") }

}

trait Goodbye {def bye { println("Bye bye!") }

}

// Object with both hello() and bye() methods..object A extends Hello with Goodbye

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 15: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Traits

Traits – Widen thin interface to richI Define one or a few abstract methodsI Define concrete methods implemented in terms of the abstract

trait Ordered[A] {abstract def compare(that: A): Intdef <(that: A): Boolean = this.compare(that) < 0def <=(that: A): Boolean = this.compare(that) <= 0...

}

class Name(val name: String) extends Ordered[Name] {def compare(that: Name) = this.name.compare(that.name)

}

if(name1 <= name2) { ... // val name1 = new Name("Ola")

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 16: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Traits

Traits – Define stackable modificationsI Modify methods of a classI Stack several modifications with each other

abstract class IntQueue {def get: Intdef put(x: Int)

} // + concrete impl IntQueueImpl

trait PutPrint extends IntQueue {abstract override def put(x: Int) {println("Put: " + x)super.put(x)

}}

val printQueue = new IntQueueImpl with PutPrint

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 17: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Generics and Abstract Types

GenericsI Classes and traits can be generifiedI Generics/type parameterization impl with erasure (like Java)I Type parameters are required (not like Java)I Variance – nonvariant, covariant and contravariantI Upper and lower bounds

trait Set[T] { // Nonvariantdef contains(elem: T): Boolean...

trait Set[+T] // Covarianttrait Set[-T] // Contravariant

trait OrderedSet[T <: Ordered[T]] // Upper boundtrait Array[+T] {def indexOf[S >: T](elem: S): S // Lower bound

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 18: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Generics and Abstract Types

Abstract types

I Types as abstract members

I Much like type parameterization, different usage

I Generic types – reusable containers, collections ++

I Abstract types – premade subclasses, hides implementation

abstract class OrderedSet {type DType <: Ordered[DType]...

class IntSet extends OrderedSet {type DType = RichInt...

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 19: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Introduction to Functional Programming

Functional programming

I Scala goal: Mix OO and FPI Some FP characteristics:

I Higher-order functionsI Function closure supportI Recursion as flow controlI Pure functions – no side-effectsI Pattern matchingI Type inferrence/implicits

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 20: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Introduction to Functional Programming

Mutable/immutable

I Immutable data structures important in FP

I Pure function – same result with same arguments

I Scala uses keywords var and val

I Immutable definitions (val) encouraged

val num = 45 // Immutable - allways 45num = 60 // Error: reassignment to val

var num2 = 45 // Mutable - can be changednum2 = 60 // Ok

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 21: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Functions

Scala functionsI Higher-order functions – args and resultsI Objects that implement scala.FunctionN traitsI Special syntax support with => operator

// Three equivalent definitions to find even numbersval f1 = new Function[Int, Boolean] { // Full versiondef apply(i: Int) = i % 2 == 0

}val f2 = (i: Int) => i % 2 == 0 // Special operatordef f3(i: Int) = i % 2 == 0 // Regular function definition

// Usage (f1, f2 and f3 equivalent)f1(64) // Converts to f1.apply(64)val arr = Array(1, 2, 3, 4)arr.filter(f1) // Returns Array(2, 4)

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 22: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Functions

Closures/anonymous functions

I Scala – Anonymous functions

I Like anonymous classes in Java (and Scala)

I Nothing special with closures – just passing function object

I The (underscore) can be used to anonymize arguments

val arr = Array(1, 2, 3, 4)

arr.filter((i: Int) => i % 2 == 0) // Returns Array(2, 4)arr.filter(_ % 2 == 0) // Shorter version using _

arr.map(_ % 2) // Returns Array(1, 0, 1, 0)

arr.foreach(print _) // Prints "1234"

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 23: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Functions

Partially applied functions and curryingI Partially applied functions – leave args outI Currying – multiple argument lists

// Partially applied functiondef sum(i: Int, j: Int) = i + jval fivePlus = sum(5, _: Int) // New func with 1 argfivePlus(6) // Result 11

val myprint = print _ // Example from previous slidemyprint("hello world!")

// Currying exampledef curriedSum(i: Int)(j: Int) = i + jcurriedSum(2)(3) // Result 5val fivePlus = curriedSum(5)_ // New func with 1 argfivePlus(6) // Result 11

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 24: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Pattern Matching

Pattern matching

I Like switch statements on steroidsI Kinds of patterns:

I Wildcard patterns – the char againI Constant patterns – numbers, strings ++I Variable patterns – namesI Constructor patterns – case classesI Sequence patterns – all sequence classes (List, Array ++)I Tuple patterns – all tuplesI Typed patterns – like function arguments

I Variable binding – using the @ sign

I Pattern guards – adding an if clause

I Pattern overlaps – case order is important!

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 25: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Pattern Matching

Pattern matching – Basic example

def desc(x: Any) = x match {case 5 => "five" // Constant patterncase i: Int => "int: " + i.toString // Typed patternscase s: String => "str: " + scase (a, b) => "tuple: " + a + b // Tuple patterncase _ => "unknown" // Wildcard/default pattern

}

desc(8) // "int: 8"desc("Scala") // "str: Scala"desc(5) // "five"desc(("Eivind", 32)) // "tuple: Eivind32"desc(4.0) // "unknown"

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 26: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Pattern Matching

Pattern matching – Case classes exampleI Factory method + all params are valI Methods toString, hashCode and equals added

case class Person(name: String, age: Int)

def greet(x: Any) = x match {case Person("Eivind", 32) => "Hello creator!"case Person(n, a) if a < 32 => "Hello young " + ncase Person(n, _) => "Hello " + ncase _ => "Hello whatever"

}

greet(Person("Ola", 80)) // Hello Olagreet(Person("Ola", 5)) // Hello young Olagreet("Eivind") // Hello whatevergreet(Person("Eivind", 32)) // Hello creator!

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 27: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Pattern Matching

Pattern matching – List example

def desc(x: Any) = x match {case List(_: String, _: String) => "List of two strings"case List(_, _) => "List of two elems"case head :: _ => "List starting with " + headcase _ => "Whatever"

}

desc(List(1, 2)) // List of two elemsdesc(List(1, 2, 3)) // List starting with 1desc(List("hello", "world")) // List of two strings

// Note! Two equivalent defs - "Error: unreachable code"case head :: _ => "List starts with " + headcase List(head, _*) => "List starts with " + head

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 28: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Other Functional Concepts

For expressionsI Generators, definitions and filtersI Can yield value – Range classI A rewrite of methods map, flatMap and filter

for (l <- "letters") println(l) // Split with linefor (num <- 1 until 10) print(num) // Prints "123456789"

for {p <- persons // Generatorn = p.name // Definitionif(n startsWith "E") // Filter

} yield n

// Two generators - with ( and ; to compactfor (n <- 1 to 3; l <- "xyz") yield n.toString + l

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 29: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Interesting Tidbits

Actors api

I Simplify concurrent programming

I Hides threads – message based

I Immutable objects and functional style recommended!

import scala.actors.Actor._val helloActor = actor {while (true) {receive {case msg => println("hello message: " + msg)

}}

}helloActor ! "Hello World!!"

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 30: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Interesting Tidbits

Continuations

I Coming in Scala 2.8I Typical tasks:

I Asynchronous I/O with Java NIOI Executors and thread poolsI Cross-request control flow in web applications

I New library functions, not keywords – shift and reset

I Complicated – different mindset

reset {shift { k: (Int => Int) =>k(k(k(7)))

} + 1} * 2 // result: 20

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 31: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Interesting Tidbits

Java integrationI Java is called from Scala directlyI @scala.reflect.BeanProperty annotation

import java.util.Dateval d = new Date

I Scala compiles to standard Java bytecodeI Singleton objects – combo of static and instance methodsI Traits – interface + ancillary classI Operators – methods with special names

def +(other: RichInt) = ... // Scala

public RichInt \$plus(RichInt other) { ... } // Java

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala

Page 32: Introduction to Scala

Outline Introduction Concise Syntax Object Orientation Functional Programming Various Stuff Conclusion

Rounding It Up

Conclusion

I Object orientation and functional programming combined

I Static and compiled – benefits, not obstacles

I Rich syntax – Java-code / 3?

I Seamless integration with Java – run in existing environment

I Big momentum – the ”new” Java?

More Info:

http://www.scala-lang.org/

Eivind Barstad Waaler BEKK/UiO

Introduction to Scala