Introduction to Scala

download Introduction to Scala

If you can't read please download the document

description

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

Transcript of Introduction to Scala

  • 1. ScalaLorenzo DemattTrenta3devMateriale basato su esempi diAlf Kristian Style, Micheal Stal, ed altri

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. 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. 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. 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. List persons = ...List adults = new LinkedList();List kids = new LinkedList();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. 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. TipiScalas: Stringi: IntJavaString sint i / Integer i 9. Variabilivar i: Int = 42 10. Variabilivar i = 42 // type inferencei = 3i = "Hello world!" // tipizzazione statica 11. Valori (~costanti)val i = 42i = 3 // errore di compilazione 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. Metodidef sum(a: Int, b: Int): Int = {return a + b} 14. Metodidef sum(a: Int, b: Int): Int = {a + b} 15. Metodidef sum(a: Int, b: Int) = {a + b} 16. Metodidef sum(a: Int, b: Int) = a + b 17. Metodipublic String hello;public String getHello(){ }public void setHello(String s) { } 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. 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. Metodi"apple".charAt(0)"apple" charAt 01.0.+(2.0)1.0 + 2.0 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. 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. myObject match {case 1 => println("Primo")case 2 => println("Secondo")case _ => println("Orru...")}Pattern matching 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. val email = """(.+)@(.+)""".r"[email protected]" match {case email(name, domain) =>println("User " + name + " at " + domain)case x => println(x + " is not an email")}Pattern matching 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. FunzioniPredicate even = new Predicate() {@Overridepublic boolean apply(Integer i) {return i % 2 == 0;}};List numbers = // 1, 2, 3, 4Iterable evenNums =Iterables.filter(numbers, even);=> [2, 4]Google collections: 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. Funzionival numbers = List(1, 2, 3, 4)val evenNums = numbers.filter((i: Int) => i % 2 == 0)=> List(2, 4)Scala collections: 30. Funzionival numbers = List(1, 2, 3, 4)val evenNums = numbers.filter(i => i % 2 == 0)=> List(2, 4)Scala collections: 31. Funzionival numbers = List(1, 2, 3, 4)val evenNums = numbers.filter(_ % 2 == 0)=> List(2, 4)Scala collections: 32. FunzioniPredicate even = new Predicate() {@Overridepublic boolean apply(Integer i) {return i % 2 == 0;}};val evenNums = numbers.filter(_ % 2 == 0) 33. FunzioniPredicate even = i -> i % 2 == 0Java8 lambda expressions:val even = (i: Int) => i % 2 == 0Scala functions: 34. FunzioniIterables.filter(numbers, i -> i % 2 == 0)Java8 lambda expressions:numbers.filter(_ % 2 == 0)Scala functions: 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. 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. Interfacce funzioniali e lambdahelloButton.addActionListener(e =>println(Hello World!)) 38. Closuresval people = List(Person(Alice), Person(Orru))val name = Orruval nameFilter = (p: Person) => p.name == namepeople.filter(nameFilter) // Person(Orru) 39. Closuresval people = List(Person(Alice), Person(Orru))var name = Orruval nameFilter = (p: Person) => p.name == namepeople.filter(nameFilter) // Person(Orru)name = Alicepeople.filter(nameFilter) // Person(Alice) 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. 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-demandcomputing Simile a lazy (che, tra parentesi, pure ce inScala) APIs performanti, e intuitive particolarmente per lecollection 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 String) {println(debug)if (logLevel (that: A): Boolean = (this compare that) > 0def = 0} 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 // false 52. Generici Ricordate lequivalenza strutturale? 53. Dynamic mixinsclass 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. 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. def using[T A) = {try {f(closeable)} finally {if (closeable != null) {try {closeable.close()}catch {case e: Exception => // Do something clever!?}}}} 56. For-loopsScala:for (i 0.0 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. 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. Esempio: scala.List head :: tailval list = List(1, 2)val myList = 1 :: 2 :: Nil// 0 :: 1 :: 2 :: Nilval myotherList = 0 :: myList 63. Cercare di essere puri Concorrenza Iterator.par. Facile evitare errori NullPointerException Facile da testare scala.collection.immutable ...oppure scala.collection.mutable!