Your First Program
The club secretary wants to try Scala today, not next week. Getting from nothing to a running program takes three things: the tools, one file and one command. Once those work, every later lesson is just more lines in that file.
The rule
Install once, write a
@mainfunction, run it withscala run.
Install once. Scala's official installer is Coursier, a command called cs. Download it for your system from the Scala website, then run cs setup. It installs a Java runtime if you do not have one, plus the scala command and related tools. Check that it worked:
scala --versionWrite a @main function. Create a file called hello.scala:
@main def hello(): Unit =
println("Riverside Run Club: logbook open")def hello()defines a function namedhellowith no parameters.@mainmarks it as the place where the program starts. Without it, there is nothing to run.: Unitsays the function returns no useful value; it is run for its effect, printing a line.- The body is the indented line after
=. Scala 3 uses the indentation to see where the function ends.
Run it with scala run.
scala run hello.scalaThe command compiles the file to JVM bytecode and then starts it. The first run is slower because the compiler is downloaded and cached; later runs reuse it. To compile without running, use scala compile hello.scala.
A @main function can take parameters, and Scala fills them from the words you type after --:
@main def welcome(name: String): Unit =
println(s"Welcome to the club, $name")scala run welcome.scala -- AshaThis prints Welcome to the club, Asha. Leave the name out and the program stops with a message that more arguments were expected.
The shortcut
Treat setup as a loop with four beats: check, write, run, change. If a beat fails, the error tells you which beat to repeat.
Check
scala --versionprints a version number. If the command is not found, reruncs setupand open a new terminal.
The common first-day mistakes are a missing @main, so the runner finds no entry point, and program arguments placed before --, where the scala command treats them as more files to compile.
Drills
Answer fast — trust the rule.
What does the @main annotation do?
Which command compiles and runs hello.scala?
@main def welcome(name: String): Unit — how do you pass the name Asha?
What does the return type Unit tell you about hello()?
What is cs setup for?
Remember
- Install with
cs setup, write a@mainfunction, run it withscala run file.scala. - Shortcut: check, write, run, change.
- Trap: no
@mainmeans no entry point, and program arguments go after--.
