Scala Notes Section 1- 7

Option[A] is a container for an option value of type A. If the value of type A is present, the Option[A] is an instance of Some[A], containing the present value of A. If the value is absent , the Option[A] is the object of None.
An object is a singleton. One object, that’s it. This object is a replacement of static in Java, and is called upon much in the same way.
An object that has the same name as a class is called a companion object of the class, and it is often used to contain factory methods for the class that it complements
class Movie(val name: String, val year: Short)
object Movie {
def academyAwardBestMoviesForYear(x: Short) = {
//This is a match statement, more powerful than a Java switch statement!
x match {
case 1930 ⇒ Some(new Movie(“All Quiet On the Western Front”, 1930))
case 1931 ⇒ Some(new Movie(“Cimarron”, 1931))
case 1932 ⇒ Some(new Movie(“Grand Hotel”, 1932))
case _ ⇒ None
Movie.academyAwardBestMoviesForYear(1932) should be()
A companion object can also see private values and variables of the corresponding classes’ instantiated objects
class Person(val name: String, private val superheroName: String) //The superhero name is private!
object Person {
def showMeInnerSecret(x: Person) = x.superheroName
val clark = new Person(“Clark Kent”, “Superman”)
val peter = new Person(“Peter Parker”, “Spiderman”)
val bruce = new Person(“Bruce Wayne”, “Batman”)
val diana = new Person(“Diana Prince”, “Wonder Woman”)
Person.showMeInnerSecret(clark) should be(“Superman”)
Scala tuple combines a fixed number of items together so that they can be passed around as a whole. They are one indexed. Unlike an array or list, a tuple can hold objects with different types but they are also immutable. 
Tuples may be of mixed type: val tuple5 = (“a”, 1, 2.2, new Date(), “five”)
You can assign multiple variables at once using tuples:
val student = (“Sean Rogers”, 21, 3.5)
val (name, age, gpa) = student
Tuples items can be swapped on a Tuple 2: val tuple = (“apple”, 3).swap

Anonymous functions in source code are called function literals and at run time, function literals are instantiated into objects called function values.
Scala supports first-class functions, which means you can express functions in function literal syntax, i.e., (x: Int) => x + 1, and that functions can be represented by objects, which are called function values

def lambda = { x: Int ⇒ x + 1 }
def lambda2 = (x: Int) ⇒ x + 1
val lambda3 = (x: Int) ⇒ x + 1
val lambda4 = new Function1[Int, Int] {
def apply(v1: Int): Int = v1 + 1
def lambda5(x: Int) = x + 1
val result = lambda(3)
val result1andhalf = lambda.apply(3)
var incrementer = 1
def closure = {
x: Int => x + incrementer
val result1 = closure(10)
Function returning another function using an anonymous function: def addWithSyntaxSugar(x: Int) = (y: Int) ⇒ x + y
Function taking another function as parameter. Helps in composing functions:
def makeUpper(xs: List[String]) = xs map {
def makeWhatEverYouLike(xs: List[String], sideEffect: String ⇒ String) = {
xs map sideEffect

Scala Lists are quite similar to arrays which means, all the elements of a list have the same type but there are two important differences.
Fistr, lists are immutable, which means elements of a list cannot be changed by assignment.
Second, lists represent a linked list whereas arrays are flat. The type of a list that has elements of type T is written as List[T].

eq tests identity (same object)
== tests equality (same content)

val a = List(1, 2, 3)
val b = List(1, 2, 3)
(a eq b) should be(false)
(a == b) should be(true)

Nil lists are identical, even of different types
val a: List[String] = Nil
val b: List[Int] = Nil
(a == Nil) should be(true)
(a eq Nil) should be(true)
(b == Nil) should be(true)
(b eq Nil) should be(true)
(a == b) should be(true)
(a eq b) should be(true)

Lists can be accessed via head, headOption and tail. Accessing List via head is unsafe and may result in a IndexOutOfBoundsException
Lists have many useful methods
val a = List(1, 3, 5, 7, 9)

// get the length of the list
a.length should equal(5)
// reverse the list
a.reverse should equal(List(9,7,5,3,1))
// map a function to double the numbers over the list { v ⇒ v * 2 } should equal(List(2,6,10,14,18))
// filter any values divisible by 3 in the list
a.filter { v ⇒ v % 3 == 0 } should equal(List(3,9))

Lists can be reduced with a mathematical operation
val a = List(1, 3, 5, 7)
a.reduceLeft(_ + ) should equal(16)
* _) should equal(105)

val a = List(1, 3, 5, 7)
// NOTE: foldLeft uses a form called currying that we will explore later
a.foldLeft(0)(_ + ) should equal(16)
+ _) should equal(26)

You can create a list from a range
val a = (1 to 5).toList // List(1,2,3,4,5)
val b = (1 until 5).toList // List(1,2,3,4)

A Map is an Iterable consisting of pairs of keys and values (also named mappings or associations).
Scala’s Predef class offers an implicit conversion that lets you write key -> value as an alternate syntax for the pair (key, value). For instance Map(“x” -> 24, “y” -> 25, “z” -> 26) means exactly the same as Map((“x”, 24), (“y”, 25), (“z”, 26)), but reads better.
The fundamental operations on maps are similar to those on sets. They are summarized in the following table and fall into the following categories:
– Lookup operations apply, get, getOrElse, contains, and isDefinedAt. These turn maps into partial functions from keys to values. The fundamental lookup method for a map is: 
def get(key): Option[Value]. The operation “m get key” tests whether the map contains an association for the given key. If so, it returns the associated value in a Some. If no key is defined in the map, get returns None.
Maps also define an apply method that returns the value associated with a given key directly, without wrapping it in anOption. If the key is not defined in the map, an exception is raised.
Additions and updates +, ++, updated, which let you add new bindings to a map or change existing bindings. – Removals -, –, which remove bindings from a map.
Subcollection producerskeys, keySet, keysIterator, values, valuesIterator, which return a map’s keys and values separately in various forms. – Transformations filterKeys and mapValues, which produce a new map by filtering and transforming bindings of an existing map.

Maps contain distinct pairings:

val myMap = Map(“MI” → “Michigan”, “OH” → “Ohio”, “WI” → “Wisconsin”, “MI” → “Michigan”)
myMap.size should be(3)
Maps can be added to easily:

val myMap = Map(“MI” → “Michigan”, “OH” → “Ohio”, “WI” → “Wisconsin”, “MI” → “Michigan”)
val aNewMap = myMap + (“IL” → “Illinois”)
aNewMap.contains(“IL”) should be(true)

Map values can be iterated:

val myMap = Map(“MI” → “Michigan”, “OH” → “Ohio”, “WI” → “Wisconsin”, “MI” → “Michigan”)

val mapValues = myMap.values // Iterable[String] = MapLike(Michigan, Ohio, Winsconsin)
mapValues.size should be(3)
mapValues.head should be(“Michigan”) //Failed presumption: The order in maps is not guaranteed

val lastElement = mapValues.last
lastElement should be(“Wisconsin”)

If a map key is requested using myMap(missingKey) which does not exist a NoSuchElementException will be thrown. Default values may be provided using either getOrElse or withDefaultValue for the entire map.

val myMap = Map(“MI” → “Michigan”, “OH” → “Ohio”, “WI” → “Wisconsin”, “IA” → “Iowa”)
intercept[NoSuchElementException] {myMap(“TX”)}
myMap.getOrElse(“TX”, “missing data”) should be(“missing data”)

val myMap2 = Map(“MI” → “Michigan”, “OH” → “Ohio”, “WI” → “Wisconsin”, “IA” → “Iowa”) withDefaultValue “missing data”
myMap2(“TX”) should be(“missing data”)

Map elements can be removed easily:

val myMap = Map(“MI” → “Michigan”, “OH” → “Ohio”, “WI” → “Wisconsin”, “IA” → “Iowa”)
val aNewMap = myMap – “MI”
aNewMap.contains(“MI”) should be(false)
myMap.contains(“MI”) should be(true)

Map elements can be removed in multiple/ a tuple

val myMap = Map(“MI” → “Michigan”, “OH” → “Ohio”, “WI” → “Wisconsin”, “IA” → “Iowa”)
val aNewMap = myMap — List(“MI”, “OH”) OR
val aNewMap = myMap – (“MI”, “OH”)

aNewMap.contains(“MI”) should be(false)
myMap.contains(“MI”) should be(true)
aNewMap.contains(“WI”) should be(true)
aNewMap.size should be(2)
myMap.size should be(4)

Attempted removal of nonexistent elements from a map is handled gracefully:

val myMap = Map(“MI” → “Michigan”, “OH” → “Ohio”, “WI” → “Wisconsin”, “IA” → “Iowa”)
val aNewMap = myMap – “MN”

aNewMap.equals(myMap) should be(true)
Map equivalency is independent of order:

val myMap1 = Map(“MI” → “Michigan”, “OH” → “Ohio”, “WI” → “Wisconsin”, “IA” → “Iowa”)
val myMap2 = Map(“WI” → “Wisconsin”, “MI” → “Michigan”, “IA” → “Iowa”, “OH” → “Ohio”)

myMap1.equals(myMap2) should be(true)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s