Chapter 1. Getting Started with the Scalable Language
The Scala programming language has a wonderfully continental ring to its name, as befits its origins at the École polytechnique fédérale de Lausanne (EPFL) in Lausanne, Switzerland. The Scala logo represents a circular stairway, which may lead you to believe its origin is the term La Scala, meaning a staircase or ladder in Italian, or that it derives from the famous Italian opera house Teatro alla Scala. In fact the name Scala is an abbreviation of the term SCAlable LAnguage, a fitting description of its intention. Professor Martin Odersky and his group at EPFL created the language in 2003 to provide a high-performance, concurrent-ready environment for functional programming and object-oriented programming on the Java Virtual Machine (JVM) platform.
Now that you have the background story, let’s install Scala and try it out.
As a JVM language, Scala requires the use of a Java runtime. Scala 2.11, the version you’ll be using, needs at least Java 6. However, I recommend installing the Java 8 JDK (aka Java SE for Standard Environment) instead for optimal performance. You can download the Java 8 JDK (or a later version, if available) for most platforms directly from Oracle’s website. Installers are available, so you shouldn’t need to manually configure your PATH variable to get the applications installed.
$ java -version java version "1.8.0_05" Java(TM) SE Runtime Environment (build 1.8.0_05-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode)
Now that Java is installed, it’s time to install Scala. There are two ways to install Scala (or any other fine programming tool): the manual approach, suitable for command-line heroes who like to modify their system’s environment variables, and the automatic approach, for the rest of us.
To install Scala manually, download the Scala 2.11 distribution from http://www.scala-lang.org and add its “bin” directory to your path. The distribution includes the Scala runtimes, tools, compiled libraries, and source, but the most important item we’ll need is the
scala command. This command provides (among other features) the REPL (Read-Eval-Print-Loop) shell we will use to learn and experiment with the Scala language.
To install Scala automatically, use a package manager such as Homebrew for OS X, Chocolatey for Windows, or apt-get/Yum for Linux systems. These are freely available and will handle finding the package, downloading and extracting it, and installing it so you can access it from the command line. The scala package is available in all of these package managers as “scala,” so you can install it with
When installed, execute the
scala command from the command line. You should see a welcome message like the following (although your Scala and Java version messages may be different):
$ scala Welcome to Scala version 2.11.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_05). Type in expressions to have them evaluated. Type :help for more information. scala>
When you see the Welcome to Scala message and the
scala> prompt you are now in the Scala REPL and are ready to start coding.
If the command is found but there are problems launching it, make sure your Java command is installed correctly and that your system path points to the correct Java version.
Using the Scala REPL
If you have used other REPL shells like Python’s python, Ruby’s irb, or Groovy’s groovysh you’ll find the Scala REPL familiar. As with the REPL’s provided with the Python, Ruby, and Groovy runtimes, Scala’s REPL provides support for evaluating and executing code one line at a time with helpful feedback.
If you haven’t used a REPL, or are just unaccustomed to writing code outside an IDE or editor, it will take some practice to learn how to develop in the Scala REPL. However, it provides an unsurpassed way to learn and experiment quickly and responsively with the Scala language and libraries. You can enter single lines of code to evaluate and compile, and any variables you create are available for the lifetime of your session. A multiline paste mode supports entering multiple lines of code to be compiled together (instead of individually), and external source code and libraries can be loaded at any time. A help system is available and can be started by entering the
Let’s get started using the REPL by implementing the classic first exercise of all serious programming books, the “Hello World” application. Start up the REPL and make sure you see the
scala> prompt on your screen:
After the prompt type
println("Hello, World!") and press Return. The REPL will run your
println() command and print the output on a line below your command. Following the printout will be another
scala> prompt, waiting for a new command to run. This is the Read, Evaluate, Print, Loop behavior from which the REPL derives its name.
Here is how the input and response should appear in the REPL:
scala> println("Hello, World") Hello, World scala>
Congratulations, you have now written and executed Scala code.
println() function, universally available to all Scala code, prints a message to the JVM’s stdout stream. When used in application servers that stdout stream is typically logged to a file (e.g., Tomcat’s catalina.out), but in the Scala REPL the
println() function’s messages appear directly in the REPL.
You can use standard readline-style up-arrow and down-arrow keys to navigate to the previous and next input lines. For example, press the up-arrow key and hit Return to rerun the previous command, or press up arrow and enter a new message to print. REPL history is stored between sessions, so you can quit, run the
scala command again, and press up arrow to access your previous commands.
scala> 5 * 7 res0: Int = 35 scala>
This time your Scala command did not print output, but instead returned a value, the product of 5 and 7. When your commands return (or are themselves) values, the REPL will assign them to a new, constant variable so that you can refer to the value in later operations. These “res” variables (a shortened version of “result,” perhaps) are sequentially numbered so that there will always be a unique container for your command’s result.
res0 contains the output of the multiplication command, lets make use of it. Type
2 * res0 at a fresh prompt and press Return. You should see something like this:
scala> 2 * res0 res1: Int = 70 scala>
As expected, the REPL recognized the
res0 variable it previously created in your arithmetic expression, and generated a new variable
res1 to store the result of the new expression.
I hope you’ve seen how using the Scala REPL to evaluate and experiment with code provides an enriched learning environment for this programming language. As you continue through this book, keep the REPL open and use it to validate everything you learn. The code samples throughout the book are presented as raw captures of REPL sessions to both validate that they work and what they print out, and also to make it easier for you to replicate them in your own REPL session.
Even better, modify and rework code examples until they break. Scala is a compiled, statically typed language, so the REPL (which compiles a line after you hit Return) will let you know immediately if you have entered incorrect Scala code or not. This will help you pick up the language more quickly and better understand the limits of its syntax and features.
println()is a good way to print a string, can you find a way to print a string without
println? Also, what kinds of numbers, strings, and other data does the REPL support?
- In the Scala REPL, convert the temperature value of 22.5 Centigrade to Fahrenheit. The conversion formula is cToF(x) = (x * 9/5) + 32.
- Take the result from exercise 2, halve it, and convert it back to Centigrade. You can use the generated constant variable (e.g., “res0”) instead of copying and pasting the value yourself.
The REPL can load and interpret Scala code from an external file with the
:load <file>command. Create a new file named Hello.scala and add a command that will print a greeting, then execute it from the REPL.
Another way to load external Scala code is to paste it into the REPL in “raw” mode, where the code is compiled as if it were actually in a proper source file. To do this, type
:paste -raw, hit Return, and then paste the contents of your source file from exercise 4. After exiting “paste” mode you should see the greeting.