A Short Introduction to Scala

A Short Introduction to Scala

A Short Introduction to Scala Otfried Cheong February 22, 2018 1 Running Scala body of a function, or the body of a while-loop is a block. In Python, this so-called block structure Like Python, Scala can be executed interactively, or is indicated using indentation. Python is very much using a Scala script. To execute Scala interactively, an exception: in nearly all programming languages, just call scala from the command line. You can indentation, and in fact any white space, does not then type commands interactively, and they will be matter at all. In Scala, like in Java and C, block executed immediately: structure is indicated using braces: { and }. For example, a typical -loop may look like this: Welcome to Scala version 2.8.1.final. while scala> println("Hello World") var i = 0 Hello World while (i <= 10) { scala> println("This is fun") printf("%3d: %d\n", i, i * i) This is fun i += 1 } This is a good way to get to know a new program- ming language and to experiment with different In Java and C, all statements have to be termi- types of data. nated by a semicolon ;. In Scala, this semicolon can In most cases, however, you will want to write a nearly always be omitted when the statement ends script, consisting of Scala functions and statements at the end of the line. If you want to put several to be executed. For example, we can create a file statements on the same line, you have to separate for1.scala with the following contents: them using semicolons: def square(n : Int) { val s = "hello"; println(s) println(n + "\t: " + n * n) } The precise rule for line endings is the following: A line ending is considered to terminate a statement for (i <- 1 to 10) (like a semicolon) unless square(i) • the line ends with a word or operator that is not legal as the end of a statement (like an infix We can run this script with the command operator or a period), or scala for1.scala. • the next line starts with a word that cannot We will see later that there is a third way to exe- start a new statement, or cute Scala programs, namely to create one or more • the line ends while inside parenthesis (...) or files that are compiled using the Scala compiler. brackets [...]. The advantage is that such a compiled programs starts much faster. 3 Dynamic and static typing 2 Syntax Every piece of data handled by a Scala program is an object. Every object has a type. The type of an Comments in Scala look like in Java and C: Every- object determines what we can do with the object. thing after a double-slash // up to the end of the Examples of objects are numbers, strings, files, and line is a comment. A long comment that continues digital images. over several lines can be written by enclosing it in A variable is a name assigned to an object during /* and */. the execution of a program. The object currently Programming languages allow you to group to- assigned to a name is called the value of the name gether statements into blocks. For instance, the or variable. 1 In dynamically typed programming languages like Python, the same name can be assigned to all /* This is C */ kinds of different objects: int m = 17; float f = 17.0; # This is Python! m = 17 # int Scala makes our life easier and our code shorter m = "seventeen" # str by using type inference. If Scala can detect what m = 17.0 # float the type of a variable name should be, then we do not need to indicate the type: This is flexible, and makes it easy to quickly write some code. It also makes it easy to make mistakes, scala> var m : Int = 17 // ok though. If you assign an object of the incorrect m: Int = 17 type, you only find out during the execution of the scala> var n = 18 // also ok! program that something doesn't work|you get a n: Int = 18 runtime error. scala> var f = 19.5 Scala is a statically typed language. This means f: Double = 19.5 that a variable can only be assigned to objects of scala> var h = "Hello World" one fixed type, the type of the variable: h: java.lang.String = Hello World var m : Int = 17 m = 18 // ok Note how the interactive Scala interpreter tells you m = "seventeen" // error! what the type of the name is even though we have m = 18.0 // error! not indicated it at all. When you are not sure if it is okay to omit the type of a name, you can always The advantage of a statically typed language is write it. that the compiler can catch type errors during the compilation, before the program is even run. A 4 val variables and var variables good compiler can also generate more efficient code for a statically type language, as the type of objects Scala has two different kinds of variables: val vari- is already known during the compilation. Consider ables and var variables. val stands for value, and the following Python function: a val variable can never change its value. Once you have defined it, its value will always remain # This is Python! the same: def test(a, b): print(a + b) val m = 17 m = 18 // error! The + operator here could mean integer addition, float addition, string concatenation, or list concate- A var variable, on the other hand, can change its nation, depending on the type of the parameters a value as often as you want: and . The code created for this function must look b var n = 17 at the types of the arguments and determine which n = 18 // ok method to call. Now consider the following Scala function: So why are val variables useful? Because they def test(a : Int, b : Int) { make it easier to understand and to discuss a pro- println(a + b) gram. When you see a val variable defined some- } where in a large function, you know that this vari- able will always have exactly the same value. If the Here it is clear to the compiler that the + opera- programmer had used a var variable instead, you tor means integer addition, and so the code for the would have to carefully go through the code to find function can immediately add the two numbers. out if the value changes somewhere. Other statically typed languages are Java, C, and It is considered good style in Scala to use val C++. One disadvantage of statically typed lan- variables as much as possible. guages is that one has to write type names every- where, leading to code that is much more verbose 5 Some basic data types than code in, say, Python. Indeed, in languages like Java or C, the programmer has to write down the The most important basic types you will need first type for every variable she uses: are: 2 Int An integer in the range −231 to 231 − 1. 6 Operators Boolean Either true or false (be careful: dif- Scala's numerical operators are +, -, /, and %. Like ferent from Python, in Scala these are written in Python 2, Java, and C, the division operators / with small letters). and % perform an integer division if both operands Double A floating-point representation of a real are integer objects. Note that there is no power number. operator in Scala (you can use the math.pow library Char A single character. To create a Char object, function to do exponentiation). write a character enclosed in single quotation You can use the shortcuts +=, -=, etc. marks, like 'A'. Scala supports Unicode char- You can compare numbers or strings using ==, acters, so a Char object can also be a Hangul !=, <, >, <=, and >=. syllable. The boolean operators are ! for not, && for and, String A sequence of Char. To create a String and for or, as in C and Java. (These some- object, write a string enclosed in double quo- || what strange operators were invented for C in the tation marks. Scala also supports the triple- early 1970s, and have somehow survived into mod- quote syntax from Python to create long ern programming languages.) Like in Python, Java, strings possibly containing new-line characters. and C, these operators only evaluate their right You will sometimes see that Scala indicates the type hand operand when the result is not already known of a string as java.lang.String. Since Scala runs from the value of the left hand operand. using the Java virtual machine and can use Java li- Sooner or later, you may meet the bitwise op- braries, Scala uses Java strings for compatibility. erators: &, |, ^, ~, <<, >>, and >>>. They work We can just write String to indicate the string on the bit-representation of integers. (A common type. mistake is to try to use ^ for exponentiation|it Special characters can be placed in Char and does something completely different, namely a log- String literals using a backslash. For instance, \n ical exclusive-or.) Don't use these operators unless is a new-line character, \t a tabulator, \' and \" you know what you are doing. are single and double quotes, and \\ is a backslash The equality and inequality operators == and != character. (Inside triple-quote strings, the back- can be used for objects of any type, even to compare slash is not interpreted like this!) objects of different type. A list of important String-methods is in Ap- One of the great features of Scala is that you can pendix A.

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    9 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us