Penn CIS 700 - Getting Started with Scala Lecture

Unformatted text preview:

Getting Started with ScalaHello WorldCommentsTypesDeclaring variables and values“Statements”Familiar statement typesThe for comprehensionArraysSimple List operationsTuplesAn aside...abbreviationsMapsSimple function definitionsFunctions are first-class objectsFunctions as parametersHigher-order methods on ListsMore higher-order methodsPattern matchingThe Option typeThe require and assert methodsDealing with exceptionsFile I/OUse the source, LukeThe EndJan 13, 2019Getting Started with ScalaHello World/** Everybody’s first program */object HelloWorld { def main(args: Array[String]) { println("Hello, World!") }}Save on a file named HelloWorld.scalaCompile with scalac HelloWorld.scala (or from your IDE)Run with scala HelloWorld (or from your IDE)Generate documentation with scaladoc HelloWorld.scalaThe above code creates a single objectEverything in the object is like Java’s staticScala doesn’t have staticScala does have classes; we’ll get to those later2Comments// and /*...*/ comments are as in Java/** Scaladoc comments are similar to Javadoc * comments. As in Javadoc, the first sentence * is a summary sentence, and additional * sentences give more detail. However, the * formatting convention is slightly different, * and wiki markup is used in preference to * HTML markup. Most of the same flags * (@author, etc.) are used. */def doNothing = ()TypesThe type hierarchy is a lattice, not a treeThat is, it has a “bottom” as well as a “top”Any AnyVal Boolean, Char, Byte, Short, Int, Long, Float, Double Scala has no primitives—these are objectsUnit (has only a single value, ()Unit is returned by functions that “don't return anything” (e.g. println)AnyRef (corresponds to Object in Java) All Java reference types, for example, StringScalaObject All Scala reference types, including Array and ListNull (bottom of all AnyRef objects)Nothing (bottom of Any)4Declaring variables and valuesThe syntax is var name: type = value // declares a variable val name: type = value // declares a valueValues are immutable: they can’t be changedThe : type can almost always be left off—the type is inferred from the valueThe = value must (almost) always be suppliedThis also works: var x: Double = 5Rules for alphanumeric names are just like in JavaBut there are other kinds of names Scope rules are just like in Java Capitalization conventions are just like in JavaArithmetic, comparison, and logical operators are just like in JavaIndentation is 2 spaces, not 4, but is otherwise the same as in Java5“Statements”Scala’s “statements” should really be called “expressions,” because almost every statement has a valueFor example, the value of a = 5 is 5The value of many statements, for example the while loop, is ()() is a value of type Unit() is the only value of type Unit() basically means “Nothing to see here. Move along.”The value of a block, {…}, is the last value computed in the blockA statement is ended by the end of the line (not with a semicolon) unless it is obviously incompleteFor example, x = 3 * (2 * y + is obviously incompleteBecause Scala lets you leave out a lot of unnecessary punctuation, sometimes a line that you think is complete really isn’t complete (or vice versa)You can end statements with semicolons, but that’s not good Scala practice6Familiar statement typesThese are the same as in Java (but have a value):variable = expression // also +=, *=, etc.The value of the statement is the value of the variablewhile (condition) { statements }The value of the statement is ()do { statements } while (condition)The value is ()if (condition) { statements }The value is the value of the last statement executedif (condition) { statements } else { statements }Older descriptions of Scala say that the else is required. It isn’t--if omitted and the condition is false, the value of the if statement is ()7The for comprehensionScala’s for is much more powerful than Java’s forConsequently, it is used much more often than the other kinds of loops We will just cover some simple cases herefor (i <- 1 to 10) { println(i) }Prints the numbers 1 through 10for (i <- 1 until 10) { println(i) }Prints the numbers 1 through 9for (x <- 0 until myArray.length) { println(myArray(x)) }Prints all the values in myArrayfor (x <- myArray) { println(x) }Prints all the values in myArrayfor (x <- myArray if x % 2 == 0) { println(x) }Prints all the even numbers in myArrayArrays Arrays in Scala are parameterized typesArray[String] is an Array of Strings, where String is a type parameterIn Java we would call this a “generic type”When no initial values are given, new is required, along with an explicit type:val ary = new Array[Int](5)When initial values are given, new is not allowed:val ary2 = Array(3, 1, 4, 1, 6)Arrays in Scala are just another kind of object; they have no special syntaxScala’s Lists are more useful, and used more often, than Arraysval list1 = List(3, 1, 4, 1, 6)val list2 = List[Int]() // An empty list must have an explicit typeSimple List operationsBy default, Lists, like Strings, are immutableOperations on an immutable List return a new ListBasic operations:list.head (or list head) returns the first element in the listlist.tail (or list tail) returns a list with the first element removedlist(i) returns the ith element (starting from 0) of the listlist(i) = value is illegal (immutable, remember?)value :: list returns a list with value appended to the frontlist1 ::: list2 appends (“concatenates”) the two listslist.contains(value) (or list contains value) tests whether value is in list An operation on a List may return a List of a different typescala> "abc" :: List(1, 2, 3)res22: List[Any] = List(abc, 1, 2, 3)There are over 150 built-in operations on Lists--use the API!TuplesScala has tuples, up to size 22 (why 22? I have no idea.)scala> val t = Tuple3(3, "abc", 5.5)t: (Int, java.lang.String, Double) = (3,abc,5.5)scala> val tt = (3, "abc", 5.5) tt: (Int, java.lang.String, Double) = (3,abc,5.5)Tuples are referenced starting from 1, using _1, _2, ...scala> t._1res28: Int = 3t _1 also works (the dot is optional)Tuples, like Lists,


View Full Document

Penn CIS 700 - Getting Started with Scala Lecture

Documents in this Course
Lists

Lists

19 pages

Actors

Actors

30 pages

Load more
Download Getting Started with Scala Lecture
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Getting Started with Scala Lecture and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Getting Started with Scala Lecture 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?