CSE116的学习笔记-Lec#2:Scala Basics cont'
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
scala
1 | val a: Int = 27397129 |
Long
- A whole number (like int)
- 64 bit representation
- -9223372036854775808 to 9223372036854775808
- Useful when you expect values that would overflow an Int
scala
1 | val a: Long = 27397129 |
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!
scala
1 | val epsilon: Double = 0.00000001 |
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
scala
1 | package example |
For Loop
scala
1 | for (<variable_name> <- <data_structure>){ |
scala
1 | package example |
For Loop + String Example
scala
1 | package example |
Reading Files
scala
1 | package example |
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
scala
1 | def arrayExample(): Unit = { |
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]
scala
1 | def listExample(): Unit = { |
Map
- Key-Value Store
- Values stroed at keys instead of indices
- Multiple different implementations
- Default is HashMap (CSE250 topic)
- Variable Size
- Variable Values
scala
1 | def mapExample(): Unit = { |
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————–
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment
TwikooValine
Powered By Valine
v1.5.1
v1.5.1