Introduction to Scala
Short Description
Download Introduction to Scala...
Description
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
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
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Introducing Scala
What is Scala?
100% Object-oriented
Functional programming
Typing: static, strong, inferred/implicits Java bytecode → JVM
.NET (CLR) Also available
Extensibility
Java-like Java-like syntax → Scala syntax
Current version 2.7.5
Eivind Barstad Waaler
→
2.8
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Introducing Scala
A first example class IntMath(val IntMath(val x: Int, Int, val y: Int) { def sum(): Int = { x + y; } def m u l = x * y } val test test = new IntMat IntMath(3 h(3, , 4) println(test.x) // ou outp tput ut: : 3 println(test.sum) // ou outp tput ut: : 7 println(test.mul()) // ou outp tput ut: : 12
Eivind Barstad Waaler
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Introducing Scala
The Scala Interpreter
An interactive “shell” for writing Scala expressions
Automatically creates temporary result variables
Simply type ’scala’ at the command prompt Using Maven2:
scala:console’ Type ’ mvn scala:console Starts the Scala Interpreter with project classpath
Demo
Eivind Barstad Waaler
⇒
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Syntax Examples
Imports
Like Java, but more features Can be anywhere Import from packages, classes or objects
import import import import
java.util._ // Al All l java.util.{ArrayList,HashSet} // Sel Select ected ed java.util.{ArrayList => _, _} // Al All l ex exce cept pt java.util.ArrayList._ // All from AL
val list list = new ArrayList import list._ // Al All l fr from om ob obje ject ct li list st import java.sql.{Date => SDate} // Ren Renami aming ng import java.util.Date Eivind Barstad Waaler
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Syntax Examples
Method syntax
. and () can be omitted for binary/unary methods
Methods can have any name
Operators are simply methods
→
full operator overloading
2.max(5) // max of 2 and 5 2 max 5 // sa same me as abov above e class def } val x val y val z
MyNumber(val MyNumber(val num: num: Int) Int) { +(othe +(other: r: MyNumb MyNumber) er) = new MyNumb MyNumber( er(oth other. er.num num + num) num) = new MyNumber(5) = new MyNumber(6) = x + y
Eivind Barstad Waaler
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Syntax Examples
Type inferrence/implicits
If type is obvious – no need to write it Implicits can be defined Implicits heavily used in std lib (RichInt etc.)
// Ty Type pe in infe ferr rren ence ce val a = 4 2 // Type = Int val b = "he "hello llo wor world! ld!" " // Ty Type pe = St Stri ring ng def add(x: Int, y: Int) = x + y // Re Retu turn rn-t -typ ype e = In Int t val sum = add(3, 5) // Type of sum = Int // Imp Implic licits its class MyInt(val MyInt(val i: Int) { def doubleIt = i * 2 } implic imp licit it def from fromIn Int( t(i: i: Int) Int) = new MyInt(i) 5.doubleIt // = 10 Eivind Barstad Waaler
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
OO Introduction
Object Orientation
Pure OO – everything is an object
Classes – blueprints for objects (like Java)
Singleton objects
Traits – AOP like possibilities
Semicolon inference
Eivind Barstad Waaler
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Classes and Objects
Scala Class Hierarchy
Eivind Barstad Waaler
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Classes and Objects
Classes
Much like Java Contains fields and methods – can override eachother
override keyword mandatory
Can take parameters directly – constructor
class A(val A(val num: num: Int) Int) class B(num: B(num: Int, Int, val str: str: String String) ) extends A(nu A(num) m) { def calc() = num * num // calc is a method } class C(nu C(num: m: Int, Int, str: str: Stri String ng) ) extends B(nu B(num, m, str) str) { overri ove rride de val calc = 65 // ov over erri ride de me meth thod od wi with th va val l } val a = new A(35) // Type A val b = new B(32, "Eivind") "Eivind") // Type B - calc method val b2: B = new C(32, "Eivind" "Eivind") ) // Also type B - calc val Eivind Barstad Waaler
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Classes and Objects
Singleton Objects
No static members in Scala → Singleton Objects Keyword object instead of class Companion class/object – same name
Factory methods Other unique/static behaviour
// Ar Arra ray y cl clas ass s de defi fini niti tion on final fin al cla class ss Array[A](_le Array[A](_length: ngth: Int) extends Array0[A] // Ar Arra ray y ob obje ject ct defi defini niti tion on wi with th me meth thod od object Arra Array y { def appl apply( y(xs xs: : Int* Int*): ): Arra Array[ y[In Int] t] = { ... ... } } // Cr Crea eate te arra array y wi with th fo four ur in inte tege gers rs val arr = Array(1, 2, 3, 4) Eivind Barstad Waaler
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Classes and Objects
The “magic” apply()-method
Scala provides special syntax for calling the apply() method In classes used to look up elements (for instance in Collections) In objects used to create class instances Functions in Scala are actually just apply() methods Make your classes/objects appear as built-in syntax
// Ar Arra ray y ob obje ject ct ha has s ap appl ply y me meth thod od fo for r cr crea eati ting ng ar arra rays ys def appl apply( y(xs xs: : Int* Int*): ): Arra Array[ y[In Int] t] = { ... ... } // Ar Arra ray y cl clas ass s ha has s ap appl ply y me meth thod od to ac acce cess ss th the e ar arra ray y def appl apply( y(i: i: Int) Int): : A // Sc Scal ala a sp spec ecia ial l sy synt ntax ax val arr = Array(4, 3, 2, 1) // Ar Arra ray. y.ap appl ply( y(4, 4, 3, 2, 1) val thre three e = arr( arr(1) 1) // arr arr.ap .apply ply(1) (1) Eivind Barstad Waaler
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Traits
Traits
Encapsulates method and field definitions, much like classes A class can mix in any number of traits → multiple multiple inheritance inheritance Widen thin interfaces to rich ones Define stackable modifications
trait Hell Hello o { def hell hello o { prin printl tln( n("Hello!" "Hello!") ) } } trait Good Goodby bye e { def bye bye { prin printl tln( n("B "Bye ye by bye! e!" ") } } // Ob Obje ject ct wi with th bo both th he hell llo( o() ) an and d by bye( e() ) me meth thod ods. s.. . object A extends Hello with Goodbye Eivind Barstad Waaler
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Traits
Traits – Widen thin interface to rich
Define one or a few abstract methods Define concrete methods implemented in terms of the abstract
trait Ordere Ordered[A d[A] ] { abstra abs tract ct def compar compare(t e(that hat: : A): Int def "s "str tr: : " + s case (a, (a, b) => "t "tup uple le: : " + a + b // Tu Tupl ple e pa patt tter ern n case _ => "unknown" // Wil Wildca dcard/ rd/def defaul ault t pat patter tern n } desc(8) // "i "int nt: : 8" desc("Scala" desc("Scala") ) // "s "str tr: : Sc Scal ala" a" desc(5) // "f "fiv ive" e" desc(("Eivind" desc(("Eivind", , 32)) 32)) // "tu "tuple ple: : Eiv Eivind ind32" 32" desc(4.0) // "un "unkno known" wn"
Eivind Barstad Waaler
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Pattern Matching
Pattern matching – Case classes example
Factory method + all params are val Methods toString, hashCode and equals added
case ca se cl clas ass s Person Person(na (name: me: String String, , age: age: Int) Int) def gree greet( t(x: x: Any) Any) = x match { case Person("Eivind" Person("Eivind", , 32) => "He "Hello llo cre creato ator!" r!" case Person Person(n, (n, a) if a < 3 2 => "H "Hel ello lo yo youn ung g " + n case Person Person(n, (n, _) => "H "Hel ello lo " + n case _ => "He "Hello llo wha whatev tever" er" } greet(Person("Ola" greet(Person("Ola", , 80)) 80)) // He Hell llo o Ol Ola a greet(Person("Ola" greet(Person("Ola", , 5)) // He Hell llo o yo youn ung g Ol Ola a greet("Eivind" greet("Eivind") ) // He Hell llo o wh what atev ever er greet(Person("Eivind" greet(Person("Eivind", , 32)) 32)) // He Hell llo o cr crea eato tor! r! Eivind Barstad Waaler
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Pattern Matching
Pattern matching – List example def desc desc(x (x: : Any) Any) = x match { case List List(_ (_: : Stri String ng, , _: Stri String ng) ) => "L "Lis ist t of tw two o st stri ring ngs" s" case List List(_ (_, , _) => "L "Lis ist t of tw two o el elem ems" s" case head :: _ => "L "Lis ist t st star arti ting ng wi with th " + head head case _ => "Whatever" } desc(L desc(List ist(1, (1, 2)) // List of two elems desc desc(L (Lis ist( t(1, 1, 2, 3)) 3)) // Li List st st star arti ting ng wi with th 1 desc(List("hello" desc(List("hello", , "world" "world")) )) // Li List st of tw two o st stri ring ngs s // No Note te! ! Tw Two o eq equi uiva vale lent nt de defs fs - "E "Err rror or: : un unre reac acha habl ble e co code de" " case head :: _ => "L "Lis ist t st star arts ts wi with th " + head head case List(h List(head ead, , _*) => "L "Lis ist t st star arts ts wi with th " + head head
Eivind Barstad Waaler
BEKK/UiO
Outline
Introduction
Concise Syntax
Object Orientation
Functional Programming
Various Stuff
Conclusion
Other Functional Concepts
For expressions
Generators, definitions and filters Can yield value – Range class A rewrite of methods map, flatMap and filter
for (l
View more...
Comments