scala-slides

简单介绍了Scala语言的作者以及特点和运行环境以及由哪些基础语言组成
展开查看详情

1.An Introduction to FUNCTI NAL OBJECT - ORIENTED Apostolos N. Papadopoulos (papadopo@csd.auth.gr) Assistant Professor Data Engineering Lab Department of Informatics Aristotle University of Thessaloniki Thessaloniki – Greece

2. The Very Basics “If I were to pick a language to use today other than Java, it would be Scala.” —James Gosling (father of Java) 2

3. The Very Basics Scala = SCAlable LAnguage i.e., designed to grow with the demands of its users Development started in 2001 by Martin Odersky and his team at EPFL First release in January 2004 Current version 2.11.6 3

4. The Very Basics Scala is a general-purpose programming language that runs on Java Virtual Machine (JVM) and .NET Expresses common programming patterns in a concise, elegant, and type-safe way. Scala supports both the object-oriented and the functional programming model. 4

5. The Very Basics Scala is object-oriented: – Encapsulation – Inheritance – Polymorphism – All predefined types are objects – All user-defined types are objects – Objects communicate by message exchange 5

6. The Very Basics Scala is functional: – Functions are first-class values – Can define a function in another function – Can map input values to output values – Can do lazy evaluation – Supports pattern matching – Higher-order functions Scala is not a PURE functional language however. 6

7. The Very Basics Scala has been inspired by other programming languages:  Scala's object model was pioneered by Smalltalk and taken up subsequently by Ruby  Scala adopts a large part of the syntax of Java and C#  Its idea of universal nesting (almost every construct in Scala can be nested inside any other construct) is also present in Algol, Simula, and, more recently in Beta  Its uniform access principle for method invocation and field selection comes from Eiffel  Its approach to functional programming is quite similar in spirit to the ML family of languages, which has SML, OCaml, and F# as prominent members  It adopts the Actor model for concurrent computation from Erlang 7

8. The Very Basics Simula Lisp objects Prolog C functional Smalltalk programming syntax pattern matching ML C++ Erlang Haskell Java Actors Scala 8

9. The Very Basics Scala is a statically typed language like Java. In static typing, a variable is bound to a particular type for its lifetime. Its type can’t be changed and it can only reference type-compatible instances. That is, if a variable refers to a value of type A , you can’t assign a value of a different type B to it, unless B is a subtype of A , for some reasonable definition of “subtype.” This is different than in dynamically typed languages such as Ruby, Python, Groovy, JavaScript, Smalltalk and others. 9

10. Scala vs Java Java code: class Book { private String author; private String title; private int year; public Book(String author, String title, int year) { this.author = author; this.title = title; this.year = year; } public void setAuthor(String author) { this.author = author; } public void String getAuthor() { return this.author; } public void setTitle(String title) { this.title = title; } public void String getTitle() { return this.title; } public void setYear(int year) { this.age = year; } public void int getYear() { return this.year; } } Scala code: class Book (var author: String, var title: String, var year: Int) 10

11. Scala vs Java Lets check it out: class Book (var author: String, var title: String, var year: Int) Assume the previous class declaration is in the file Book.scala We run the Scala compiler using scalac Book.scala Then, we use the class disassembler $JAVA_HOME/bin/javap -private Book.class 11

12. Scala vs Java public class Book { private java.lang.String author; private java.lang.String int title; private int year; public java.lang.String author(); public void author_$eq(java.lang.String); public java.lang.String title(); public void title_$eq(java.lang.String); public int year(); public void year_$eq(int); public Book(java.lang.String, int); } 12

13. The First Scala Program A very simple program in Scala: /* Our first Scala program */ object HelloWorld { /* The main function */ def main(args: Array[String]) { println("Hello, world!") } } To define a singleton we use the keyword object 13

14. Scala Data Types Byte 8 bit signed value, Range from -128 to 127 Short 16 bit signed value. Range -32768 to 32767 Int 32 bit signed value. Range -2147483648 to 2147483647 Long 64 bit signed value. -9223372036854775808 to 9223372036854775807 Float 32 bit IEEE 754 single-precision float Double 64 bit IEEE 754 double-precision float Char 16 bit unsigned Unicode character. Range from U+0000 to U+FFFF String a sequence of Chars 14

15. Simple Functions // count from 1 to 10 def countTo(n: Int) { for (i <- 1 to 10) { println(i) } } // return true if a number is even, false otherwise def isEven(n: Int) = { val m = n % 2 m == 0 } 15

16. Immutable vs Mutable An immutable element cannot change its value. Immutable elements help in creating more robust parallel programs because concurrency is much more easier for immutable values. A mutable element can change its value. Scala supports both immutable and mutable elements and it is up to the program to use these features. e.g., val pi = 3.14 // pi is immutable, is defined as a val (value) var sal = 10,000 // sal is mutable, it is defined as a var (variable) 16

17. Imperative vs Functional Imperative programming is the way we program in C, C++, Java and similar languages. It is heavily based on mutable elements (i.e., variables) and we need to specify every single step of an algorithm. Scala supports imperative programming, but the real power of the language is the functional perspective which is based on immutable elements. 17

18. Interactive Scala The REPL (Read – Evaluate – Print Loop) It is a Scala Shell Useful for fast testing, without the need to write complete programs. Runs each scala command immediately. 18

19. Interactive Scala A screenshot of the Scala REPL 19

20. First Steps in Scala Define a list of pets: val pets = List("dog", "cat", "parrot") Print the contents of the list: pets.foreach(println) Print the length of each string: pets.foreach(pet => println(pet.length)) 20

21. First Steps in Scala Split a sentence to words val msg = "Hello World" msg.split(" ").foreach(println) Result: Hello World 21

22. First Steps in Scala val msg = "Polytechnique" msg.drop(3).take(2).capitalize Result: Yt 22

23. First Steps in Scala Iterate over string characters val msg = "hello polytechnique" msg.map(c => c.toUpper) Result: HELLO POLYTECHNIQUE 23

24. First Steps Scala Filtering strings val msg = "This is a text" } msg.filter(_ != 'i').map(c => c.toUpper) equivalent msg.filter(_ != 'i').map(_.toUpper) Result: THS S A TEXT 24

25. First Steps in Scala Random numbers val r = scala.util.Random r.nextInt r.nextInt(100) r.nextFloat r.nextDouble // An array of random numbers val vector = Array.fill(10){r.nextInt(9)} 25

26. First Steps in Scala List examples // List of Strings val fruit: List[String] = List("apples", "oranges", "pears") // List of Integers val nums: List[Int] = List(1, 2, 3, 4) // An empty List val empty: List[Nothing] = List() // A two-dimensional List val dim: List[List[Int]] = List(List(1, 0, 0), List(0, 1, 0), List(0, 0, 1) ) 26

27. First Steps in Scala Set examples var users = Set("Mary", "John", "Fred", "Julia") users("Mary") // returns true users("Ted") // returns false users += "Jack" // inserts “Jack” into the users users -= "Fred" // removes “Fred” from users What if we had declared val users = Set("Mary", "John", "Fred", "Julia") 27

28. Counting Lines of a File object LineCount { def main(args: Array[String]) { val inputFile = "leonardo.txt" val src = scala.io.Source.fromFile(inputFile) val counter = src.getLines().map(line => 1).sum println("Number of lines in file: "+counter) } } 28

29. WordCount v1: idea Use a hashmap, which stores (word,counter) pairs. The hashmap is updated in every word occurrence. Either a new word is inserted with counter=1, or the counter is incremented. 29