Lecture #2 9/4
授课时间:2020-09-04 13:50:00

Scala Basics cont’

Scala Types

  • All values in Scala are objects
    • Objects contain variables and methods
    • No primitive values in Scala

Int

  • A whole number
  • 32 bit representation
  • -2147483648 to 2147483648
    • values out side this range will overflow
1
2
val a: Int = 27397129
println(a)

Long

  • A whole number (like int)
  • 64 bit representation
  • -9223372036854775808 to 9223372036854775808
  • Useful when you expect values that would overflow an Int
1
2
val a: Long = 27397129
println(a)

Double

  • Number with a whole number and a decimal portion
  • 64 bit representataion
  • Values are truncated to fit in 64 bit
    • Loss of precision!
    • 0.1 doesn’t exit!
1
2
3
4
5
val epsilon: Double = 0.00000001
val b: Double = 0.1
val c: Double = b * 3
val expected: Double = 0.3
println(Math.abs(c - 0.3)< epsilon)

Boolean and Unit

  • Boolean
    • true or false
  • Unit
    • Nothing
    • Used to indicate a method / function that does not return a value

String

  • A sequence of characters (type Char)
  • Declared with double quotes " "
    • val s: String = “nice”
  • Many useful methods.
    • startsWith()
    • length() - number of String
    • .split() - Separates this String by given String
      • line.split(“#”)

Scala Type Conversions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package example

object Types {

def main(args: Array[String]): Unit = {

// Declaring variable
var anInt: Int = 10
var aDouble: Double = 5.8
var aBoolean: Boolean = true
var aString: String = "6.3"

// Converting variable types
var anotherDouble: Double = aString.toDouble
var anotherString: String = anInt.toString

// Truncates the decimal. anotherInt == 5
var anotherInt: Int = aDouble.toInt
}
}

For Loop

1
2
3
for (<variable_name> <- <data_structure>){
<loop_body>
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package example

object Loop {

def printOneTo(n: Int): Unit = {
for(i <- 1 to n){
println("i == " + i)
}
}

def printOneToAlternate(n: Int): Unit = {
val numbers: Range = 1 to n
for(i <- numbers) {
println("i == " + i)
}
}

def main(args: Array[String]): Unit = {
printOneTo(10)
}
}

For Loop + String Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package example

object StringSplitter {

def computPercentTrue(line: String): Double = {
val splits: Array[String] = line.split(":")
var totalCount: Double = 0
var trueCount: Double = 0
for (value <- splits) {
val valueAsBoleean: Boolean = value.toBoolean
if (valueAsBoleean){
trueCount += 1
}
totalCount += 1
}
trueCount / totalCount
}

def main(args: Array[String]): Unit = {
val testInput = "true;false;true;true;ture"
val percenTrue = computePercentTrue(testInput) // expecting 0.8
println("Percentage true == " + percentTrue)
}
}

Reading Files

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package example

import scala.io.{BufferedSource, Source}

object FileReader {

def convertFileToString(filename: String): String = {
var contents: String = ""
val file: BufferedSource = Source.fromFile(filename)
for (line <- file.getLines()) {
contents += line + "\n"
}
contents
}

def main(args: Array[String]): Unit = {
val filename = "data/testFile.txt"
val contents = convertFileToString(filename)
println(contents)
}
}

Data Structures

Array

  • Sequential
    • One continuous block of memory
    • Random access based on memory address
      • address = first_address + (element_size * index)
  • Fixed Size
    • Since memory adjacent to the block may be usedd
    • Efficient when you konw how many elements you’ll need to store
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def arrayExample(): Unit = {
//Create new Array of Int
val arr: Array[int] = Array(2, 3, 4)

// Change a value by index
arr(1) = 20

// Access a value by index
val x: Int = arr(1)

// Iterate over elements
for (element <- arr) {
println(element)
}

// Iterate over indices
for (index <- 0 to (arr.length - 1)) {
println(index)
}

// Iterate over indices - alternate
for (index <- arr.indices) {
println(index)
}
}

List

  • Sequential
    • Spread across memory
    • Each element knows the memory address of the next element
      • Follow the addresses to find each element
  • Variable Size
    • Store new element anywhere in memory
    • Add the new memory address to the last element
      • Or new element stores address of first element
  • Values cannot change [In Scala]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def listExample(): Unit = {
// Create new Array of Int
var list: List[Int] = List(2, 3, 4)

// Access the first element
val x: Int = list.head

// Access a value by position
val y: Int = list.apply(1)

// Add an element to the end of the list (append)
list = list :+ 50

// Add an element to the beginning of the list (prepend)
list = 70 :: list

// Iteration
for (element <- list) {
println(element)
}
}

Map

  • Key-Value Store
    • Values stroed at keys instead of indices
    • Multiple different implementations
      • Default is HashMap (CSE250 topic)
  • Variable Size
  • Variable Values
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def mapExample(): Unit = {
// Create new Map of Int to Int
var myMap: Mao[Int, Int] = Map(2 -> 4, 3 -> 9, 4 -> 16)

// Add an key-value pair
myMap = myMap + (5 -> 25)

// Access a value by key (Crashes if key not in map)
val x: Int = myMap(3)

// Accesss a value by key with default value if key not in map
val y: Int = myMap.getOrElse(100, -1)

//Iteration
for ((key, value) <- myMap) {
println("value " + vlue + " stored at ket " + key)
}
}

Lecture Question

In a package named “lecture” create an object named “LectureQuestion” with a method named “fileSum” that takes a filename as a String and returns an Int which is the sum of the values in the file.

The input file will contain multiple lines each with multiple integer values separated by the ‘#’ character

Return the sum of all of the integer values in the file

You may assume that the file exists and is properly formatted

Sample file contents:

——Sample File Contents——
3#1#8
12#9#25#10
-2#12
1#2
—————End————–