What Scala Is and Why It Exists
The Riverside Run Club wants a small program to log its members' runs: who ran, how far and how fast. Over this course you will write that logbook in Scala. Before any code, it helps to know what kind of language you are learning, because Scala's habits look odd until you know the ideas behind them.
The rule
Objects and functions together, strictly typed, and nearly everything returns a value.
Take the rule one phrase at a time.
Objects and functions together. Martin Odersky designed Scala at EPFL in Switzerland, and it was first released in 2004. In Scala, object-oriented design (classes and traits) and functional programming (functions passed around as values, data that never changes) are equally at home. The name is short for "scalable language": the same few ideas serve a ten-line script and a large system.
Strictly typed. The compiler checks every value's type before the program runs, so many mistakes are caught at your desk. You seldom write the types yourself, because Scala infers them.
Nearly everything returns a value. An if, a match, even a block of several lines produces a result you can store under a name.
val longestRun = 10.0 // the compiler infers Double
val verdict = if longestRun >= 10 then "big week" else "easy week"
println(verdict) // big weekScala mainly compiles to bytecode for the Java Virtual Machine (JVM), so it can call any Java library. Scala.js targets the browser, and Scala Native builds standalone machine-code programs.
This course uses Scala 3, released in 2021, which marks blocks with indentation instead of curly braces and writes conditions as if … then … else. You will still meet Scala 2 code with braces; most of it reads the same.
The official docs at docs.scala-lang.org hold the Scala 3 Book, a guided tour, and the API reference, where you can confirm exactly what any standard method does.
The shortcut
Faced with any unfamiliar line of Scala, ask three questions in order: What type is it? Can it change? What value does it produce? Those three questions unlock most of the language.
The line
val weekTotal = runs.sumadds up Asha's runs for the week.
The trap is reading Scala as if it were Java or Python and looking for a return statement. In Scala, the last expression of a block usually is the result.
Drills
Answer fast — trust the rule.
Which two styles of programming does Scala set out to combine?
val verdict = if 3.2 >= 10 then "big week" else "easy week" — what does verdict hold?
val weekTotal = runs.sum has no type written. What does the compiler do?
The club wants to use an existing Java charting library inside its Scala program. What is true?
Which line is written in Scala 3's own style?
Remember
- Scala combines object-oriented and functional programming, checks types before running, and infers most of them.
- Decode any line with three questions: what type, can it change, what value does it produce?
- Trap: hunting for
return— the last expression is usually the result.
