After this lab, you will be able to:
- build, run, and test an sbt project from the command line, and edit it in VS Code with the Metals extension.
- read and write the core Scala this course relies on: immutable
collections,
Option, case classes, and pattern matching – including recursion over lists and tree-shaped data, the pattern behind every compiler pass you will write. - commit, push, and submit a project through GitHub and Gradescope, the workflow used by every assignment in the course.
If you have used Scala before, treat the lab as a fast refresher and a check that your toolchain works; you should finish early. If Scala is new to you, this is a quick introduction to the language. Lab 1 and PA 1 will reinforce what is presented.
Submit your finished project on Gradescope (see Submit It at the end) — every assignment in this
course uses the same submission flow, and today is the day to work out
any kinks. The lab is done when sbt test reports no failed
tests and Gradescope agrees. Ask for help if you are stuck on anything,
especially tooling.
Before You Start
Work on the lab machines today. They have all necessary tools installed.
Send me your GitHub username if you have not already – do this first.
I will create your own copy of the starter repository
(cs434-f26-scala-crash-course-<your-github-username>
in the course organization), and GitHub will invite you to it; accept
the invitation (check your email or github.com/notifications).
Then clone the repository and go inside (copy the exact URL from the
green “Code” button on your repository’s page):
$ git clone <your repository URL>
$ cd <your repository name>
Part 1: One Project, Three Commands
Every project in this course – this lab, the homework warm-ups, and your compiler itself – is an sbt project with the same structure:
<your repository>/
build.sbt the build definition (name, Scala version, libraries)
project/build.properties pins the sbt version; never edit
src/main/scala/tour/ the program: Main.scala, Exercises.scala
src/test/scala/tour/ the tests: ExercisesTests.scala, MyTests.scala
Start sbt in the directory containing
build.sbt and leave it running; it gives you a
prompt, and each command is fast after the first one:
$ sbt
sbt> compile -- compile everything that changed
sbt> run -- run the main program (tour.Main)
sbt> test -- compile and run the unit tests
sbt> exit
The very first compile downloads the Scala compiler and
libraries, so it is slow; everything after that is quick. Three more
things worth knowing now:
~testreruns the tests automatically every time you save a file. This is the edit loop you will live in for the whole course. Press enter to get the prompt back.consolegives you an interactive Scala prompt with your code on the classpath. Try it now:sbt> console scala> 1 + 2 scala> List(1, 2, 3).map(x => x * 10) scala> :quitIf sbt ever seems confused,
cleandeletes all compiled output, and the nextcompilestarts fresh.
Part 2: Open It in VS Code
While you can use any editor after today, we’ll get started with VS Code with the Metals Scala extension. VS Code itself is on the lab machines, but extensions are installed per-user, so everyone installs Metals themselves. It takes a minute, and you only do it once:
Launch VS Code and open the Extensions panel: click the building-blocks icon in the activity bar on the left, or press cmd-shift-X (ctrl-shift-X on Windows/Linux).
Type
Metalsinto the search box at the top of the panel.Select Scala (Metals), published by Scalameta, and click its blue Install button. (Several extensions mention Scala; Metals by Scalameta is the one you want.)
When the Install button is replaced by a gear icon, the extension is installed. The first time it starts, Metals also downloads its own language-server components in the background – a progress message appears in the status bar along the bottom of the window. Let it finish before moving on.
Now choose File | Open Folder…, and open your
repository folder – the one containing build.sbt. Opening
the folder, not an individual file, is what lets Metals find
the build.
Shortly after the folder opens, Metals asks whether to import the build. Click Import build and give the first import a minute to finish. Once it does, VS Code understands your whole project: errors are underlined as you type, hovering over any expression shows its type, and cmd-click (ctrl-click on Linux) jumps to a definition. Small run and test links also appear above main methods and test suites – clicking one runs just that program or suite.
Keep the sbt prompt from Part 1 running in VS Code’s integrated
terminal (Terminal | New Terminal), so your editor and
your test loop sit side by side in one window. That combination – Metals
for editing and navigation, ~test in the terminal below –
is the setup to use for the rest of the course. If Metals ever seems
confused, run “Metals: Import build” from the command palette; the sbt
prompt is always the ground truth.
Part 3: The Guided Tour
Open src/main/scala/tour/Main.scala in VS Code and run
it:
sbt> run
The file is a commented tour, and every block of output comes from a
few adjacent lines of code. Read it top to bottom and match each line of
output to the code that printed it. The tour covers, in order: values,
if as an expression, methods, List
transformations, Set and Map,
Option, classes, case classes, and recursion over
lists.
Do not just read it – change something in each part (make a list
longer, break a type on purpose to see a compile error, add a
println) and run it again.
Part 4: Write some code
Now open src/main/scala/tour/Exercises.scala. It
contains a series of small unwritten functions; each has a body of
???, which compiles but fails at run time. The matching
tests are in src/test/scala/tour/ExercisesTests.scala, one
per exercise, in the same order. (The file beside it,
MyTests.scala, is yours; Part 5 is about it.) Start the
watch loop:
sbt> ~test
and work top to bottom. With the starter, the first test passes and the rest fail; your job is to pass all the tests. A few notes as you go:
circleArea,maxOf3: pi is the constantmath.Pi, no import needed. There is no ternary operator;if/elseis an expression that produces a value.factorial: functions can call themselves; there is no loop anywhere in this lab.applyTwice: functions are values. The parameterf: Int => Intis a function fromInttoInt, applied like any other function.squaresOfEvens: chainfilterandmap. Collections are immutable: these return new lists.sum: pattern match on the two shapes a list can have,Nilorx :: rest, exactly likecountat the bottom ofMain.scala.describe: match onNoneorSome(n); build the string with an interpolator,s"the number $n".outEdges: aMaplookup with a default, exactly likeromans.getOrElse(9, "?")in the tour.Nilis the empty list.successors:flatMapover the set, callingoutEdgeson each state. Why notmap?mapwould hand back a set of lists, one per state;flatMapsplices those lists together into the single flat set you want. This one-liner is the heart of the NFA simulator you will write in Lab 1.Stack: a class with hidden, mutable state, likeLabelsin the tour. Keep the items in aListwith the top at the head; it is immutable, sopushreplaces it withx :: items. Foraddandsub, matchitemsagainstb :: a :: rest, and fall through tocase _ =>when there are too few items. Mind the order insub:bis the top. You have built a tiny stack machine; the JVM running your Scala evaluates arithmetic on exactly such a stack.evalandshow:Expris a tiny abstract syntax tree:Add(Num(1), Mul(Num(2), Num(3)))is the tree for1 + 2 * 3. Match on the three node shapes and recurse. When these pass, pause to notice what you wrote:evalis an interpreter, andshowis a pretty printer. Larger versions of this exact pattern are will appear throughout the semester.
Part 5: Write a Test
The tests so far were written for you. From PA 1 on you will write
your own, so write two now. Open
src/test/scala/tour/MyTests.scala. It is a second test
suite, and it is yours: the autograder replaces
ExercisesTests.scala with its own copy, but runs
MyTests.scala as you wrote it. It holds one finished
example.
A test is a claim about behavior: set something up, then assert what
must be true afterwards. Add at least two tests of your
Stack that ExercisesTests.scala does not
already make. Some claims worth checking:
- pushes and pops interleaved come back in the right order;
subon an empty stack, or on a one-item stack, changes nothing;- two
adds in a row, or a longer expression such as(1 + 2) - (3 + 4), leave exactly one item, and the right one.
Give each test a name that says what it claims. Then make sure it can
fail: break sub on purpose, watch your test catch it, and
put sub back. A test that cannot fail checks nothing.
~test reruns both suites on every save.
Submit It
Every programming assignment in this course is submitted the same way: commit and push your work, then submit to Gradescope, where an autograder builds your project with sbt and runs tests against it. Practice now, while the stakes are zero:
$ git add -A
$ git commit -m "finish the crash course"
$ git push
Then upload your project to the Lab 0: Scala Crash
Course assignment on Gradescope. The autograder compiles your
project, runs the same thirteen tests you just made pass — using its own
copy of ExercisesTests.scala, so editing that file changes
nothing — and runs your MyTests.scala as you wrote it,
giving credit once at least two of your tests pass. You should see every
line green. If the autograder says something different than
sbt test said on your machine, something is off about your
project layout; sort it out now, not the night PA 1 is due.
Where This Leads
Lab 1 asks you to simulate an NFA: reading a transition table into a
Map, then repeatedly applyingsuccessors-style set operations. You have now written the hard line of it.PA 1 and beyond are all sbt projects laid out exactly like this one, with
sbt testas the workflow.For more Scala depth, the Scala 3 Book is the reference we recommend; the Lab Guide collects the course’s tooling advice in one place.