Your SlideShare is downloading. ×
0
ScalaLorenzo DemattéTrenta3devMateriale basato su esempi diAlf Kristian Støyle, Micheal Stal, ed altri
If I were to pick a language to use on the JVMtoday other than Java, it would be Scala.– James Gosling, creator of Javahtt...
Agenda● Cosa è, e perché Scala?● Introduzione a Scala– Sintassi di base– Pattern matching– Funzioni!– Classi, traits e mix...
Scala● Porgrammazione object oriented E funzionale● Tipizzazione statica● Compatibile (interoperabile) con Java– Compilazi...
public class Person {private int age;private String name;public Person(int age, String name) {this.age = age;this.name = n...
List<Person> persons = ...List<Person> adults = new LinkedList<Person>();List<Person> kids = new LinkedList<Person>();for ...
using(new BufferedReader(new FileReader("f.txt"))) {reader => println(reader.readLine())}BufferedReader reader = null;try ...
TipiScalas: Stringi: IntJavaString sint i / Integer i
Variabilivar i: Int = 42
Variabilivar i = 42 // type inferencei = 3i = "Hello world!" // tipizzazione statica
“Valori” (~costanti)val i = 42i = 3 // errore di compilazione
“Valori” (~costanti)class DbImport(private val config: Config,private val connection:() => java.sql.Connection,...) {val d...
Metodidef sum(a: Int, b: Int): Int = {return a + b}
Metodidef sum(a: Int, b: Int): Int = {a + b}
Metodidef sum(a: Int, b: Int) = {a + b}
Metodidef sum(a: Int, b: Int) = a + b
Metodipublic String hello;public String getHello(){ … }public void setHello(String s) { … }
Metodipublic String hello;public String getHello(){ … }public void setHello(String s) { … }val hello = “hello” // val s = ...
MetodiScala:myObject.myMethod(1)myObject myMethod(1)myObject myMethod 1myObject.myOtherMethod(1, 2)myObject myOtherMethod(...
Metodi"apple".charAt(0)"apple" charAt 01.0.+(2.0)1.0 + 2.0
Metodi"apple".charAt(0)"apple" charAt 01.0.+(2.0)1.0 + 2.0trait NumericalExpression[A] extends TypedExpressionNode[A] {def...
Collectionsval list = List("apple", "orange", "banana")val map = Map(1 -> "uno", 2 -> "due")val array = Array(1, 2, 3, 4, ...
myObject match {case 1 => println("Primo")case 2 => println("Secondo")case _ => println("Orru...")}Pattern matching
myObject match {case i: Int => println("Un numero " + I * 2)case s: String => println("Del testo " + s.toUpper)case _ => p...
val email = """(.+)@(.+)""".r"scala@java.no" match {case email(name, domain) =>println("User " + name + " at " + domain)ca...
val numbers = List(1, 2, 3)val secondNumber = numbers match {case List(_, i, _*) => Some(i)case _ => None}=> secondNumber:...
FunzioniPredicate<Integer> even = new Predicate<Integer>() {@Overridepublic boolean apply(Integer i) {return i % 2 == 0;}}...
Funzionival even = (i: Int) => i % 2 == 0val numbers = List(1, 2, 3, 4)val evenNums = numbers.filter(even)=> List(2, 4)Sca...
Funzionival numbers = List(1, 2, 3, 4)val evenNums = numbers.filter((i: Int) => i % 2 == 0)=> List(2, 4)Scala collections:
Funzionival numbers = List(1, 2, 3, 4)val evenNums = numbers.filter(i => i % 2 == 0)=> List(2, 4)Scala collections:
Funzionival numbers = List(1, 2, 3, 4)val evenNums = numbers.filter(_ % 2 == 0)=> List(2, 4)Scala collections:
FunzioniPredicate<Integer> even = new Predicate<Integer>() {@Overridepublic boolean apply(Integer i) {return i % 2 == 0;}}...
FunzioniPredicate<Integer> even = i -> i % 2 == 0Java8 lambda expressions:val even = (i: Int) => i % 2 == 0Scala functions:
FunzioniIterables.filter(numbers, i -> i % 2 == 0)Java8 lambda expressions:numbers.filter(_ % 2 == 0)Scala functions:
Funzioni: cittadini di prima classeval even = Function[Int, Boolean] {def apply(i: Int) = i % 2 == 0}val even: (Int => Boo...
Funzioni e collectionsnumbers.filter(i => i > 2) // List(3, 4, 5)numbers.find(i => i > 2) // Some(3)numbers.exists(i => i ...
“Interfacce funzioniali” e lambdahelloButton.addActionListener(e =>println(“Hello World!”))
Closuresval people = List(Person(“Alice”), Person(“Orru”))val name = “Orru”val nameFilter = (p: Person) => p.name == namep...
Closuresval people = List(Person(“Alice”), Person(“Orru”))var name = “Orru”val nameFilter = (p: Person) => p.name == namep...
Funzioni di ordine superiore● Funzioni che prendono funzioni comeparametri e/o ritornarno funzionidef test(numbers: List[I...
call-by-value vs. “call-by-name”● by-value: espressioni valutate prima dellachiamata● by-name: espressioni valutate allint...
call-by-value vs. call-by-nameExample: Loggingdef thisTakesTime(): String = {// leeento! Prende la stringa dal DB magari!}...
“call-by-name”def debug(s: => String) {println(“debug”)if (logLevel <= DEBUG)println(s)}
Gli “statement” hanno un valoreval numbers = for (i <- 1 to 10) yield ival res = if (cond) x else yval res2 = try { x } ca...
Classi e costruttoriScala:class Person(val name: String)Java:public class Person {private final String name;public Person(...
Classi e costruttoriclass Person(val age: Int) {def this() = this(42)var name: String = _override def toString = "Ciao, so...
GenericiScala:List[String]Java:List<String>● Equivalenza strutturale!– Tipizzazione “dinamica” con la rete di sicurezza– R...
Generici// Structural Typing (avoids us doing manual reflection)type Precompiler = {var sources: Array[File]...var info: {...
Traits (= Interface + Mixin)● “Eredita multipla fatta bene”● Si possono avere implementazioni di metodi(Java8? C# 5?)● Si ...
scala.Ordered traittrait Ordered[A] {def compare(that: A): Intdef < (that: A): Boolean = (this compare that) < 0def > (tha...
Ordered traitclass Person(val age: Int) extends Ordered[Person] {def compare(other: Person) = this.age - other.age}val per...
Generici● Ricordate lequivalenza strutturale?
“Dynamic mixins”class Person(val name: String, val age: Int) {override def toString = "My name is " + name}trait Loud {ove...
using(new BufferedReader(new FileReader("f.txt"))) {reader => println(reader.readLine())}BufferedReader reader = null;try ...
def using[T <: { def close() }, A](closeable: T)(f: T => A) = {try {f(closeable)} finally {if (closeable != null) {try {cl...
For-loopsScala:for (i <- 0 to 3) {...}for (s <- args) println(s)// args.foreach(println(_))Java:for (int i = 0; i < 4; i++...
E ci sono molte altre cose...● Tuples● Singleton objects● For-comprehensions● Implicit conversions● Actors● XML come tipo ...
TuplesScala:val tuple: Tuple2[Int, String] =(1, “apple”)val quadruple =(2, “orange”, 0.5d, false)Java:Pair<Integer, String...
ScalaTest demoval travels = travelFinder.buildTravels(trips)travels should have size 2val trips = travels.flatMap(_._2)val...
Imparare scala● Sintassi... dipende!– E facile scrivere Java-ish Scala● Il linguaggio cresce man mano che lo capiete● Vi l...
Programmazione funzionale “pura”● Funzioni “matematiche”– Niente side effects● In pratica: solo oggetti immutabili– Tutti ...
Esempio: scala.List● head :: tailval list = List(1, 2)val myList = 1 :: 2 :: Nil// 0 :: 1 :: 2 :: Nilval myotherList = 0 :...
Cercare di essere “puri”● Concorrenza– Iterator.par.● Facile evitare errori– NullPointerException● Facile da testare● scal...
Upcoming SlideShare
Loading in...5
×

Introduction to Scala

83

Published on

An overview of the Scala programming language, focusing on differences with Java and in language novelties (in Italian)

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
83
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Introduction to Scala"

  1. 1. ScalaLorenzo DemattéTrenta3devMateriale basato su esempi diAlf Kristian Støyle, Micheal Stal, ed altri
  2. 2. If I were to pick a language to use on the JVMtoday other than Java, it would be Scala.– James Gosling, creator of Javahttp://www.adam-bien.com/roller/abien/entry/java_net_javaone_which_programmingScala, it must be stated, is the current heir apparent to theJava throne. No other language on the JVM seems ascapable of being a "replacement for Java" as Scala, andthe momentum behind Scala is now unquestionable.– Charlies Nutter, JRuby leadhttp://blog.headius.com/2009/04/future-part-one.htmlMy tip though for the long term replacement of javac is Scala.Im very impressed with it! I can honestly say if someone hadshown me the Programming in Scala book […] back in 2003Id probably have never created Groovy.– James Strachan, creator of Groovyhttp://macstrac.blogspot.com/2009/04/scala-as-long-term-replacement-for.html
  3. 3. Agenda● Cosa è, e perché Scala?● Introduzione a Scala– Sintassi di base– Pattern matching– Funzioni!– Classi, traits e mixins● Qualche “chicca”● NON in queste slides (una prossima volta?):– Continuations– For-comprehensions and Monads– Parallelismo e Actors
  4. 4. Scala● Porgrammazione object oriented E funzionale● Tipizzazione statica● Compatibile (interoperabile) con Java– Compilazione in bytecode Java– Conversioni automatiche (collection, tipi base)● Mixed compilation!– … e con .NET!● “Un java migliore”?
  5. 5. public class Person {private int age;private String name;public Person(int age, String name) {this.age = age;this.name = name;}public int getAge() {return this.age;}public void setAge(int age) {this.age = age;}public String getName() {return this.name;}public void setName(String name) {this.name = name;}}class Person(var age: Int, var name: String)
  6. 6. List<Person> persons = ...List<Person> adults = new LinkedList<Person>();List<Person> kids = new LinkedList<Person>();for (Person person : persons) {if (person.getAge() < 18) {kids.add(person);} else {adults.add(person);}}val persons: List[Person] = ...val (kids, adults) = persons.partition(_.age < 18)
  7. 7. using(new BufferedReader(new FileReader("f.txt"))) {reader => println(reader.readLine())}BufferedReader reader = null;try {reader = new BufferedReader(new FileReader("f.txt"));System.out.println(reader.readLine());} finally {if (reader != null) {try {reader.close();} catch (IOException e) {// Exception on close, ignore}}}
  8. 8. TipiScalas: Stringi: IntJavaString sint i / Integer i
  9. 9. Variabilivar i: Int = 42
  10. 10. Variabilivar i = 42 // type inferencei = 3i = "Hello world!" // tipizzazione statica
  11. 11. “Valori” (~costanti)val i = 42i = 3 // errore di compilazione
  12. 12. “Valori” (~costanti)class DbImport(private val config: Config,private val connection:() => java.sql.Connection,...) {val db = Database(config,useSessionFactory = false,useConnectionPool = false)...Readonly/const (ma non propagato)
  13. 13. Metodidef sum(a: Int, b: Int): Int = {return a + b}
  14. 14. Metodidef sum(a: Int, b: Int): Int = {a + b}
  15. 15. Metodidef sum(a: Int, b: Int) = {a + b}
  16. 16. Metodidef sum(a: Int, b: Int) = a + b
  17. 17. Metodipublic String hello;public String getHello(){ … }public void setHello(String s) { … }
  18. 18. Metodipublic String hello;public String getHello(){ … }public void setHello(String s) { … }val hello = “hello” // val s = obj.hellodef hello = {println("Hello, " + name)return “hello”} // val s = obj.hello
  19. 19. MetodiScala:myObject.myMethod(1)myObject myMethod(1)myObject myMethod 1myObject.myOtherMethod(1, 2)myObject myOtherMethod(1, 2)myObject.myMutatingMethod()myObject.myMutatingMethodmyObject myMutatingMethodJava:myObject.myMethod(1);myObject.myOtherMethod(1, 2);myObject.myMutatingMethod()
  20. 20. Metodi"apple".charAt(0)"apple" charAt 01.0.+(2.0)1.0 + 2.0
  21. 21. Metodi"apple".charAt(0)"apple" charAt 01.0.+(2.0)1.0 + 2.0trait NumericalExpression[A] extends TypedExpressionNode[A] {def ===[B](b: NumericalExpression[B]) =new EqualityExpression(this, b)...def > [B](b: NumericalExpression[B]) = gt(b)...def +[B](b: NumericalExpression[B]) = plus(b)...def gt [B](b: NumericalExpression[B]) =new BinaryOperatorNodeLogicalBoolean(this, b, ">")...table.deleteWhere(ob => ob.tr_id === t.id and ob.data gt data)
  22. 22. Collectionsval list = List("apple", "orange", "banana")val map = Map(1 -> "uno", 2 -> "due")val array = Array(1, 2, 3, 4, 5)list(1) // orangemap(2) // duearray(3) // 4
  23. 23. myObject match {case 1 => println("Primo")case 2 => println("Secondo")case _ => println("Orru...")}Pattern matching
  24. 24. myObject match {case i: Int => println("Un numero " + I * 2)case s: String => println("Del testo " + s.toUpper)case _ => println("Orru...")}Pattern matching
  25. 25. val email = """(.+)@(.+)""".r"scala@java.no" match {case email(name, domain) =>println("User " + name + " at " + domain)case x => println(x + " is not an email")}Pattern matching
  26. 26. val numbers = List(1, 2, 3)val secondNumber = numbers match {case List(_, i, _*) => Some(i)case _ => None}=> secondNumber: Option[Int] = Some(2)Pattern matching
  27. 27. FunzioniPredicate<Integer> even = new Predicate<Integer>() {@Overridepublic boolean apply(Integer i) {return i % 2 == 0;}};List<Integer> numbers = … // 1, 2, 3, 4Iterable<Integer> evenNums =Iterables.filter(numbers, even);=> [2, 4]Google collections:
  28. 28. Funzionival even = (i: Int) => i % 2 == 0val numbers = List(1, 2, 3, 4)val evenNums = numbers.filter(even)=> List(2, 4)Scala collections:
  29. 29. Funzionival numbers = List(1, 2, 3, 4)val evenNums = numbers.filter((i: Int) => i % 2 == 0)=> List(2, 4)Scala collections:
  30. 30. Funzionival numbers = List(1, 2, 3, 4)val evenNums = numbers.filter(i => i % 2 == 0)=> List(2, 4)Scala collections:
  31. 31. Funzionival numbers = List(1, 2, 3, 4)val evenNums = numbers.filter(_ % 2 == 0)=> List(2, 4)Scala collections:
  32. 32. FunzioniPredicate<Integer> even = new Predicate<Integer>() {@Overridepublic boolean apply(Integer i) {return i % 2 == 0;}};val evenNums = numbers.filter(_ % 2 == 0)
  33. 33. FunzioniPredicate<Integer> even = i -> i % 2 == 0Java8 lambda expressions:val even = (i: Int) => i % 2 == 0Scala functions:
  34. 34. FunzioniIterables.filter(numbers, i -> i % 2 == 0)Java8 lambda expressions:numbers.filter(_ % 2 == 0)Scala functions:
  35. 35. Funzioni: cittadini di prima classeval even = Function[Int, Boolean] {def apply(i: Int) = i % 2 == 0}val even: (Int => Boolean) = (i: Int) => i % 2 == 0val even = (i: Int) => i % 2 == 0even.apply(42) // trueeven(13) // false
  36. 36. Funzioni e collectionsnumbers.filter(i => i > 2) // List(3, 4, 5)numbers.find(i => i > 2) // Some(3)numbers.exists(i => i > 2) // truenumbers.forall(i => i > 2) // falsenumbers.map(i => i * 2) // List(2, 4, 6, 8, 10)numbers.foldLeft(0) { (a, b) => a + b } // 15
  37. 37. “Interfacce funzioniali” e lambdahelloButton.addActionListener(e =>println(“Hello World!”))
  38. 38. Closuresval people = List(Person(“Alice”), Person(“Orru”))val name = “Orru”val nameFilter = (p: Person) => p.name == namepeople.filter(nameFilter) // Person(“Orru”)
  39. 39. Closuresval people = List(Person(“Alice”), Person(“Orru”))var name = “Orru”val nameFilter = (p: Person) => p.name == namepeople.filter(nameFilter) // Person(“Orru”)name = “Alice”people.filter(nameFilter) // Person(“Alice”)
  40. 40. Funzioni di ordine superiore● Funzioni che prendono funzioni comeparametri e/o ritornarno funzionidef test(numbers: List[Int], f: Int => Boolean) =numbers.map(tall => f(tall))// List[Boolean]
  41. 41. call-by-value vs. “call-by-name”● by-value: espressioni valutate prima dellachiamata● by-name: espressioni valutate allinterno delchiamante– Quando la valutazione e costosa, non semprenecessaria; per avere computazioni “on-demand”computing– Simile a “lazy” (che, tra parentesi, pure ce inScala)– APIs performanti, e intuitive particolarmente per lecollection
  42. 42. call-by-value vs. call-by-nameExample: Loggingdef thisTakesTime(): String = {// leeento! Prende la stringa dal DB magari!}def debug(s: String) {println(“debug”)if (logLevel <= DEBUG) println(s)}logger.debug(thisTakesTime())
  43. 43. “call-by-name”def debug(s: => String) {println(“debug”)if (logLevel <= DEBUG)println(s)}
  44. 44. Gli “statement” hanno un valoreval numbers = for (i <- 1 to 10) yield ival res = if (cond) x else yval res2 = try { x } catch { … y } finally { … }(Almost) everything is an expression
  45. 45. Classi e costruttoriScala:class Person(val name: String)Java:public class Person {private final String name;public Person(String name) {this.name = name;}public String getName() {return name;}}
  46. 46. Classi e costruttoriclass Person(val age: Int) {def this() = this(42)var name: String = _override def toString = "Ciao, sono " + name}
  47. 47. GenericiScala:List[String]Java:List<String>● Equivalenza strutturale!– Tipizzazione “dinamica” con la rete di sicurezza– Reflection? Facile!
  48. 48. Generici// Structural Typing (avoids us doing manual reflection)type Precompiler = {var sources: Array[File]...var info: {def apply(v1:String):Unit}...def execute(): Unit}val precompilerClassName = "org.fusesource.scalate.support.Precompiler"val precompiler = loader.loadClass(precompilerClassName).newInstance.asInstanceOf[Precompiler]precompiler.info = (value:String) => getLog.info(value)precompiler.sources = Array(mojo.warSourceDirectory,mojo.resourcesSourceDirectory)...precompiler.execute
  49. 49. Traits (= Interface + Mixin)● “Eredita multipla fatta bene”● Si possono avere implementazioni di metodi(Java8? C# 5?)● Si possono implementare metodi● Si possono avere metodi e campi astratti● Niente costruttori (astratte)● E possibile chiamare la classe base– Ma con controlli!
  50. 50. scala.Ordered traittrait Ordered[A] {def compare(that: A): Intdef < (that: A): Boolean = (this compare that) < 0def > (that: A): Boolean = (this compare that) > 0def <= (that: A): Boolean = (this compare that) <= 0def >= (that: A): Boolean = (this compare that) >= 0}
  51. 51. Ordered traitclass Person(val age: Int) extends Ordered[Person] {def compare(other: Person) = this.age - other.age}val person1 = new Person(21)val person2 = new Person(31)person1 < person2 // trueperson1 <= person2 // trueperson1 >= person2 // false
  52. 52. Generici● Ricordate lequivalenza strutturale?
  53. 53. “Dynamic mixins”class Person(val name: String, val age: Int) {override def toString = "My name is " + name}trait Loud {override def toString = super.toString.toUpperCase}val person = new Person("Orru", 18) with Loudprintln(person)=> MY NAME IS ORRU
  54. 54. using(new BufferedReader(new FileReader("f.txt"))) {reader => println(reader.readLine())}BufferedReader reader = null;try {reader = new BufferedReader(new FileReader("f.txt"));System.out.println(reader.readLine());} finally {if (reader != null) {try {reader.close();} catch (IOException e) {// Exception on close, ignore}}}Ricordate?
  55. 55. def using[T <: { def close() }, A](closeable: T)(f: T => A) = {try {f(closeable)} finally {if (closeable != null) {try {closeable.close()}catch {case e: Exception => // Do something clever!?}}}}
  56. 56. For-loopsScala:for (i <- 0 to 3) {...}for (s <- args) println(s)// args.foreach(println(_))Java:for (int i = 0; i < 4; i++) {...}for (String s : args) {System.out.println(s);}
  57. 57. E ci sono molte altre cose...● Tuples● Singleton objects● For-comprehensions● Implicit conversions● Actors● XML come tipo nativo● Parsers● Continuations
  58. 58. TuplesScala:val tuple: Tuple2[Int, String] =(1, “apple”)val quadruple =(2, “orange”, 0.5d, false)Java:Pair<Integer, String> tuple = newPair<Integer, String>(1, “apple”)... yeah right... ;-)
  59. 59. ScalaTest demoval travels = travelFinder.buildTravels(trips)travels should have size 2val trips = travels.flatMap(_._2)val bikeTrips = trips.filter(_.bikes.getOrElse(0) > 0)bikeTrips should not be (empty)otherTrips.size should be (2)otherTrips.map(_.id) should contain leg1.idotherTrips.map(_.id) should contain leg2.idtravels.filter(_.travelType == TravelType.Bike)should not be (empty)val bikeDistance = travels.flatMap(_._1.details).filter(_.travelType == TravelType.Bike).map(_.fareKm.getOrElse(0.0)).sumbikeDistance should be > 0.0
  60. 60. Imparare scala● Sintassi... dipende!– E facile scrivere Java-ish Scala● Il linguaggio cresce man mano che lo capiete● Vi lascia migrare gradualmente a uno stile piufunzionale● Vi lascia mantenere “strtuttura”!● Ha delle “chicche”– prese singolarmente, niente di che– Insieme...
  61. 61. Programmazione funzionale “pura”● Funzioni “matematiche”– Niente side effects● In pratica: solo oggetti immutabili– Tutti i campi sono immutabili (val)– Le chiamate ai metodi non hanno side-effects● Eh?● Hint: producono un nuovo oggetto– => tutti i metodi ritornano qualcosa, un valore!
  62. 62. Esempio: scala.List● head :: tailval list = List(1, 2)val myList = 1 :: 2 :: Nil// 0 :: 1 :: 2 :: Nilval myotherList = 0 :: myList
  63. 63. Cercare di essere “puri”● Concorrenza– Iterator.par.● Facile evitare errori– NullPointerException● Facile da testare● scala.collection.immutable– ...oppure scala.collection.mutable!
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×