Scala, lesson 2
Programs need to remember things: a player's name, a price, a score. In Scala you give a value
a name with val or var.
Prefer val. Most values in a program never need to change, and when the compiler knows a
name always means the same thing, your code is easier to reason about. Reach for var only
when something really must change over time, like a running total.
Every value in Scala has a type, and the compiler checks types before the program runs. You usually don't have to write them, because Scala infers the type from the value. You can still write it after a colon when you want to be explicit:
The ones you will use most:
| Type | Holds | Example |
|---|---|---|
Int |
2 exercises to try what you just read.
| whole numbers up to about two billion |
42 |
Long | bigger whole numbers | 42L |
Double | numbers with a decimal point | 3.14 |
Boolean | true or false | true |
String | text | "hi" |
Once a name has a type, it keeps it. A var declared as an Int cannot later hold a
String; the compiler stops you.
Names start with a letter and use camelCase: playerName, maxHealth. They are case
sensitive, so score and Score are different names. Pick names that say what the value
means, not what type it is.
For a constant that never changes and is used across your program, Scala style uses an upper
camel case name, like val MaxPlayers = 4.
Putting values inside text is so common that Scala has a shortcut. Write s right before the
opening quote, then use $name for a variable or ${...} for any expression:
The f interpolator also lets you format numbers, for example with two decimals:
You can also join strings with +: "Hello, " + name. Interpolation is usually easier to
read.
The starter declares four values for a game character. Print them on one line in exactly this format, using string interpolation:
The program reads no input.
Use a var called savings that starts at 20. Then change it three times and print it
after each step:
Expected output:
val name = "Rowan" // a val can never be reassigned
var score = 0 // a var can
score = score + 10 // fine
// name = "Ash" // compile error: reassignment to valval level: Int = 7
val price: Double = 3.5
val big: Long = 9_000_000_000L // the L suffix makes a Long; underscores are just for reading
val ready: Boolean = true
val grade: Char = 'A' // single quotes: one character
val city: String = "Lisbon" // double quotes: textval item = "tea"
val cups = 3
println(s"$cups cups of $item") // 3 cups of tea
println(s"Twice that is ${cups * 2}") // Twice that is 6val total = 7.5
println(f"Total: $total%.2f") // Total: 7.50Rowan | level 7 | 42.5 HP | mage: trueStart: 20
After deposit: 35
Doubled: 70
After snack: 62