- Notifications
You must be signed in to change notification settings - Fork404
The code examples used in Programming Scala, 2nd and 3rd Editions (O'Reilly)
License
deanwampler/programming-scala-book-code-examples
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
- Dean Wampler
- Dean Wampler'sBluesky,Mastodon, andLinkedIn accounts.
- Repo discussions
- My Book Page
- Blog about Scala 3
This repo contains all the code examples in O'Reilly'sProgramming Scala, Third Edition. (The second edition isavailable here.) There are also many code files in this distribution that aren't included in the book.
Themaster branch and the3.X.Y tag releases are for the third edition. The code examples for the second edition are still available.Download the release tagged 2.1.0 or check out therelease-2.1.0 branch. While the second edition was published for 2.11. The latest2.1.0 release andrelease-2.1.0 are updated for 2.12 and 2.13. (No morerelease-2.X.Y releases are planned.)
Warning
Scala 3 is evolving, as are the tools that support it. I try to keep themain branch up to date with the latest versions, including changing the examples as required to handle new and changed features (see, e.g.,issue #131). Hence, sometimes an example (or how to run it) will be different from what you see in the book. So, if you are reading the book and want the examples exactly as they appear there, with the same tool versions used at that time, then grab the3.0.0-final release.
In particular, running ascala command-line program has changed as of version 3.5.0. So, for example, at the top of page 12 of the book, this command is shown for running a program at the shell prompt:
$ cp="target/scala-3.0.0/classes/"$ scala -classpath $cp progscala3.introscala.Hello2 Hello Scala World!Instead, use the following, where the latest Scala version (at the time of this writing...) is3.7.4:
$ cp="target/scala-3.7.4/classes/" $ scala -classpath $cp --main-class progscala3.introscala.Hello2 -- Hello Scala World!Note the required--main-class (or-M) flag before the “main” classprogscala3.introscala.Hello2 and the-- to separatescala command arguments from your program's arguments. Change all other command-line examples in the book the same way.
However, it appears thatsbt syntax hasnot changed when usingrunMain at the SBT prompt. So, for example, the following still works as documented in the book:
runMain progscala3.introscala.Hello2 Hello Scala World!(Use ofsbt is discussed further below.)
Tip
Several sections offer troubleshooting tips if you encounter problems.
In the book's text, when an example corresponds to a file in this repo, the listing begins with a path in a comment with the following format:
// src/main/scala/progscala3.introscala.UpperMain1Following the usual conventions, tests are insrc/test/....
Use these comments shown in the book to find the corresponding source file in the repo. The repo also containsMUnit andScalaCheck unit tests to validate some of the code.
The examples include "scripts" that are intended for interactive use in thescala command-line "REPL" (read, eval, print loop), for example usingsbt console (wheresbt is the de facto build tool for Scala that I use). Other files are compiled.
To keep these different kinds of files straight and to support building withsbt, the following conventions are used for the files:
src/main/scala/.../*.scala- All Scala 3 source files built withsbt.src/test/.../*.scala- All Scala 3 test source files built and executed withsbt.src/script/.../*.scala- "Script" files that won't compile withscalac, but can be interpreted with thescalaREPL or used as a worksheet (see below).src/*/scala-2/.../*.scala- Some Scala 2 source files that won't compile with Scala 3. They are not built withsbt.
You won't find many comments in the code, except of the form// <1>, which get converted into markers corresponding to notes in the book. All the descriptions of the code are in the book, so they aren't repeated as code comments.
Some files have sections marked like this:
// tag::section1[]// end::section1[]
These are used to mark sections that are selectively included in the book. Sometimes the whole file is included in sections, while other times the file has extra bonus content that doesn't appear in the book.
To build and run the examples, all you need is a recent version of the the Java SDK andsbt. When you runsbt, it will bootstrap itself with the correct version of itself, Scala, and project dependencies, which are specified in thebuild.sbt file in the root directory and other build files in theproject directory.
Follow thesesbt installation instructions.
If you want to install Scala separately and Scala'sScaladocs, go to thescala-lang.orgGetting Started guide for details. However, this isn't required.
If you want to play with the Spark example,src/script/scala-2/progscala3/bigdata/SparkWordCount.scala, you'll need to download a Spark distribution fromspark.apache.org. Assuming that$SPARK_HOME refers to the root directory of your Spark installation, run the following command in the root directory of this repo to start the Scala REPL with Spark enabled:
$$SPARK_HOME/bin/spark-shell...scala>
Then copy and paste the content ofsrc/script/scala-2/progscala3/bigdata/SparkWordCount.scala at the prompt. After it runs, there will be a new directory,README.md.wordcount with thepartition files of the output.
Tip: For more on Spark, see my free tutorial on GitHub,spark-scala-tutorial.
Most editors and IDEs now have some sort of Scala 3 support, either "natively" or through optional plugins:
- IntelliJ: Either the Community or Ultimate additions will work. Install the Scala plugin, which has built-in support for
sbt. - Visual Studio Code: Use the newScala Metals plugin instead of older plugins.
- Eclipse Scala IDE: Old, no longer recommended.
For other IDEs and text editors, tryScala Metals first (I've used it withSublime Text, for example) or the olderENSIME project. You may also need additional, third-party tools for syntax highlighting, etc.
After installing the required plugins, load this project in your IDE, which should detect and use thesbt project automatically. For eclipse, run thesbt eclipse task to generate project files, then import them.
One reader reported a problem when trying to run examples in IntelliJ:scalac: Flag -encoding set repeatedly. I confirmed this problem (at the time; it may no longer be an issue...) and I fixed it as follows:
- Open the preferences ("cmd-," on MacOS)
- Search for "scala"
- Select "Build, Execution, Deployment > Compiler > Scala Compiler"
- Select the "sbt" configuration in the list of Scala build configurations.
- Select "Additional compiler options:".
- Remove
-encoding utf-8from the text, since it is already in thebuild.sbtfile.
After that, you should be able to select a type with amain and run it.
The same reader also reported errors where multiple occurrences of the same name in a@targetName annotation collided. I believe this happens if you usesbt in a terminal to compile and then allow IntelliJ to do its own build. There are probably two copies of the class files on the resulting runtime classpath. For example, I saw this error when attempting to runsbt console in IntelliJ'ssbt shell, but not when I usedsbt in a terminal window.
So, what worked for me was to only use the terminal to runsbt clean, then let IntelliJ build the software itself, but when I need to usesbt console, I use a terminal window.
If you like working withScala worksheets in your IDE or editor, you may be able to load any of the REPL "script" files undersrc/script as a worksheet. If your environment is more restrictive, for example about the file extension used, then run the includedbash script./make-worksheets.sh to copy all the REPL "script" examples to worksheet files. This command copies the treesrc/script tosrc/worksheet and changes the.scala extension for all the files to.worksheet.sc, the VSCode convention. These behaviors are configurable. Use the--help option to see the details. If you are using Windows and you don't havebash available, e.g., through the Linux subsystem, then modify individual files as you see fit.
See thisDotty documentation page for more information about worksheets.
After installingsbt, open a command/terminal window and run thesbt test command.
You'll see lots of output as it downloads all the dependencies, compiles the code and runs the tests. You should see[success] messages at the end.
sbt is discussed in more detail in the book and thesbt website, but a few useful commands are worth mentioning here.
If you startsbt without any arguments, it puts you into an interactive mode where you can type commands. Use control-D to exit this mode. Once at thesbt prompt (sbt:programming-scala-3rd-ed-code-examples>), try the following commands, where each# starts a comment; don't type those!
help # help on tasks and settingsclean # delete all build outputscompile # compile the source, but not test codetest # compile source and test code, if necessary and run the tests.~test # continuously compile and test when source changes are saved.console # run the Scala REPL; dependencies and code are on the CLASSPATHtasks # show the most common tasks (commands).tasks -V # REALLY show ALL tasksThe~ prefix causes the task to be run continuously each time source code changes are saved. This promotes continuous TDD (test-driven development) and is one of my favorite features!
Outside ofsbt, you could, in principle, run the REPL and load the script files manually at the prompt, for example:
$ scalascala> :load src/script/scala/progscala3/introscala/Upper1.scalaHowever, it's easier to run most of the scripts usingsbt console, becausesbt will configure theCLASSPATH with the third-party libraries and compiled code examples that a script file might use.
Also, new for the Scala 3 REPL, for thosesrc/main/... files that define one (and only one)entry point, meaning amain method (Scala 2 compatible) or annotated with@main (new Scala 3 technique), you can compile and run them in one step, for example:
$ scala src/main/scala/progscala3/introscala/UpperMain2.scala -- Hello World!HELLO WORLD!$
Note
The-- argument separator is required for Scala 3.5.0 and later. It is not used for Scala 3.4.X and earlier.
There are a lot ofscript files undersrc/script/scala/..., which are used in the book as suggestions to try in the console as you are reading the book. However, they are hard to test in the usual way. Similarly, there are many@main routines and they are also not covered by tests. So, to "semi-automate" testing them, try the following twozsh scripts, both of which take a long time to run:
check-scripts.shcheck-mains.sh
Both have--help options to see what options they accept. Both do their best to check that the output is expected, but a complication is the fact that many of the Scala scripts and "mains" have deliberate errors for illustrative purposes. Thecheck-*.sh scripts attempt to compensate for this, for example by knowing which scripts should fail and allowing them to fail "successfully", but to beabsolutely certain all the examples are running correctly, it is really necessary to visually inspect the saved output from the runs (as described in console output of thecheck-*.sh) to see if the resultslook correct.
I welcome feedback on the Book and these examples. Please post comments, corrections, etc. to one of the following places:
- This GitHub repo'sdiscussion forum orpost an issue.
- TheO'Reilly book page and theerrata page.
- Dean Wampler'sBluesky,Mastodon, orLinkedIn accounts.
There is also my dedicated site for the book where occasional updates, clarifications, corrections, and lame excuses will be posted:programming-scala.org.
Some milestones (but probably not all of them...).
| Key Dates | Description |
|---|---|
| August 11, 2014 | 2nd edition examples |
| May 27, 2019 | Updated for Scala 2.12 and 2.13 |
| June 18, 2019 | New support for Maven builds, courtesy ofoldbig |
| October 12, 2019 | Updated for Scala 2.13.1, sbt 1.3.2, and other dependencies. Also now compiles with JDK 11 |
| October 13, 2019 | Renamed the repo fromprog-scala-2nd-ed-code-examples toprogramming-scala-book-code-examples |
| December 31, 2019 | Renamed theprogscala2 package toprogscala3 and reworked most of the*.sc scripts for better testability and other improvements |
| March 1, 2020 | Completed conversion to Scala 3 |
| March 20, 2020 | Started incorporating new Scala 3 syntax, idioms |
| May 15, 2021 | Scala3.0.0 final updates. Almost done! |
| May 22, 2021 | Final updates forProgramming Scala, Third Edition! |
| July 24, 2021 | Scala 3.0.1. Notes on using IntelliJ. |
| November 6, 2021 | Scala 3.1.0 and a fix for locale settings (PR 42). |
| September 15, 2024 | Scala 3.5.0 changes, e.g. thenew Scala CLI. |
| December 21, 2024 | Scala 3.6.2 changes, supporting new syntax options. |
| June 17, 2025 | Scala 3.7.X breaking changes and fixed some old bugs in some of the "scripts". |
| September 20, 2025 | Scala 3.7.3 breaking changes. Yes, a "patch" release, but in fairness, triggered by my strict compiler flags. |
About
The code examples used in Programming Scala, 2nd and 3rd Editions (O'Reilly)
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.