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

Scala Basics

Hello Scala!

Example:

1
2
3
4
5
6
package week1.basics 
object Hello{
def main(args: Array[String]): Unit = {
println("Hello Scala!")
}
}

package week1.basics : define where this code lives.
object Hello: Objects
def main{}: Main Method
println("Hello Scala!"): Print Line

Methods Variables

1
2
3
4
5
6
7
8
9
10
11
12
package week1.basics
object FirstObject{
def multiplyBtTwo(input: Double): Double = {
input * 2.0
}

def main(args: Array[String]): Unit = {
var x: Double = 7.0
var result = multiplyBtTwo(x)
println(result)
}
}

input: input value
Double: Data type
Usually no return statements.

var: Variables declaration

Conditionals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package week1.basics
object Coditional{
def computeSize(inout: Double): String = {
val large: Double = 60.0
val medium: Double = 60.0
if (input >= large) {
"large"
} else if (input >= medium) {
"medium"
} else {
"small"
}
}

def main (args: Array[String]): Unit = {
println(computeSize(70.0))
println(computeSize(50.0))
println(computeSize(10.0))
}
}

val: Values declared with val cannot change, Reassignment causes an ERROR!
"small": means return "small"

Lecture Question

Question

In a package named “lecture” create an object named “FirstObject” with a metho named “computeShippingCost” that takes a Double representing the weight of a package as a paramater and returns a Double representing the shipping cost of the package.

Ex:
The shipping cost is ($)5 + 0.25 per pound over 30

  • Every package weighing 30 pounds or less will cost 5 to ship.
  • Ex. A package weighting 31 pounds cost 5.25 to ship
  • Ex. A package weighting 40 pounds cost 7.50 to ship