You are previewing Programming Scala.

Programming Scala

Cover of Programming Scala by Dean Wampler... Published by O'Reilly Media, Inc.
  1. Programming Scala
    1. SPECIAL OFFER: Upgrade this ebook with O’Reilly
    2. A Note Regarding Supplemental Files
    3. Foreword
    4. Preface
      1. Welcome to Programming Scala
      2. Conventions Used in This Book
      3. Using Code Examples
      4. Safari® Books Online
      5. How to Contact Us
      6. Acknowledgments
    5. 1. Zero to Sixty: Introducing Scala
      1. Why Scala?
      2. Installing Scala
      3. For More Information
      4. A Taste of Scala
      5. A Taste of Concurrency
      6. Recap and What’s Next
    6. 2. Type Less, Do More
      1. In This Chapter
      2. Semicolons
      3. Variable Declarations
      4. Method Declarations
      5. Inferring Type Information
      6. Literals
      7. Tuples
      8. Option, Some, and None: Avoiding nulls
      9. Organizing Code in Files and Namespaces
      10. Importing Types and Their Members
      11. Abstract Types And Parameterized Types
      12. Reserved Words
      13. Recap and What’s Next
    7. 3. Rounding Out the Essentials
      1. Operator? Operator?
      2. Methods Without Parentheses and Dots
      3. Domain-Specific Languages
      4. Scala if Statements
      5. Scala for Comprehensions
      6. Other Looping Constructs
      7. Conditional Operators
      8. Pattern Matching
      9. Enumerations
      10. Recap and What’s Next
    8. 4. Traits
      1. Introducing Traits
      2. Stackable Traits
      3. Constructing Traits
      4. Recap and What’s Next
    9. 5. Basic Object-Oriented Programming in Scala
      1. Class and Object Basics
      2. Parent Classes
      3. Constructors in Scala
      4. Nested Classes
      5. Visibility Rules
      6. Recap and What’s Next
    10. 6. Advanced Object-Oriented Programming In Scala
      1. Overriding Members of Classes and Traits
      2. Companion Objects
      3. Case Classes
      4. Equality of Objects
      5. Recap and What’s Next
    11. 7. The Scala Object System
      1. The Predef Object
      2. Classes and Objects: Where Are the Statics?
      3. Sealed Class Hierarchies
      4. The Scala Type Hierarchy
      5. Linearization of an Object’s Hierarchy
      6. Recap and What’s Next
    12. 8. Functional Programming in Scala
      1. What Is Functional Programming?
      2. Functional Programming in Scala
      3. Recursion
      4. Tail Calls and Tail-Call Optimization
      5. Functional Data Structures
      6. Traversing, Mapping, Filtering, Folding, and Reducing
      7. Pattern Matching
      8. Partial Functions
      9. Currying
      10. Implicits
      11. Implicit Function Parameters
      12. Call by Name, Call by Value
      13. Lazy Vals
      14. Recap: Functional Component Abstractions
    13. 9. Robust, Scalable Concurrency with Actors
      1. The Problems of Shared, Synchronized State
      2. Actors
      3. Actors in Scala
      4. Traditional Concurrency in Scala: Threading and Events
      5. Recap and What’s Next
    14. 10. Herding XML in Scala
      1. Reading XML
      2. Writing XML
      3. Recap and What’s Next
    15. 11. Domain-Specific Languages in Scala
      1. Internal DSLs
      2. External DSLs with Parser Combinators
      3. Recap and What’s Next
    16. 12. The Scala Type System
      1. Reflecting on Types
      2. Understanding Parameterized Types
      3. Variance Under Inheritance
      4. Type Bounds
      5. Nothing and Null
      6. Understanding Abstract Types
      7. Path-Dependent Types
      8. Value Types
      9. Self-Type Annotations
      10. Structural Types
      11. Existential Types
      12. Infinite Data Structures and Laziness
      13. Recap and What’s Next
    17. 13. Application Design
      1. Annotations
      2. Enumerations Versus Pattern Matching
      3. Thoughts On Annotations and Enumerations
      4. Using Nulls Versus Options
      5. Exceptions and the Alternatives
      6. Scalable Abstractions
      7. Effective Design of Traits
      8. Design Patterns
      9. Better Design with Design By Contract
      10. Recap and What’s Next
    18. 14. Scala Tools, Libraries, and IDE Support
      1. Command-Line Tools
      2. Build Tools
      3. Integration with IDEs
      4. Test-Driven Development in Scala
      5. Other Notable Scala Libraries and Tools
      6. Java Interoperability
      7. Java Library Interoperability
      8. Recap and What’s Next
    19. A. References
    20. Glossary
    21. Index
    22. About the Authors
    23. Colophon
    24. SPECIAL OFFER: Upgrade this ebook with O’Reilly

A Taste of Scala

It’s time to whet your appetite with some real Scala code. In the following examples, we’ll describe just enough of the details so you understand what’s going on. The goal is to give you a sense of what programming in Scala is like. We’ll explore the details of the features in subsequent chapters.

For our first example, you could run it one of two ways: interactively, or as a “script.”

Let’s start with the interactive mode. Start the scala interpreter by typing scala and the return key on your command line. You’ll see the following output. (Some of the version numbers may vary.)

Welcome to Scala version (Java ...).
Type in expressions to have them evaluated.
Type :help for more information.


The last line is the prompt that is waiting for your input. The interactive mode of the scala command is very convenient for experimentation (see The scala Command-Line Tool for more details). An interactive interpreter like this is called a REPL: Read, Evaluate, Print, Loop.

Type in the following two lines of code:

val book = "Programming Scala"

The actual input and output should look like the following:

scala> val book = "Programming Scala"
book: java.lang.String = Programming Scala

scala> println(book)
Programming Scala


The first line uses the val keyword to declare a read-only variable named book. Note that the output returned from the interpreter shows you the type and value of book. This can be very handy for understanding complex declarations. The second line prints the value of book, which is “Programming Scala”.


Experimenting with the scala command in the interactive mode (REPL) is a great way to learn the details of Scala.

Many of the examples in this book can be executed in the interpreter like this. However, it’s often more convenient to use the second option we mentioned, writing Scala scripts in a text editor or IDE and executing them with the same scala command. We’ll do that for most of the remaining examples in this chapter.

In your text editor of choice, save the Scala code in the following example to a file named upper1-script.scala in a directory of your choosing:

// code-examples/IntroducingScala/upper1-script.scala

class Upper {
  def upper(strings: String*): Seq[String] = { => s.toUpperCase())

val up = new Upper
Console.println(up.upper("A", "First", "Scala", "Program"))

This Scala script converts strings to uppercase.

By the way, that’s a comment on the first line (with the name of the source file for the code example). Scala follows the same comment conventions as Java, C#, C++, etc. A // comment goes to the end of a line, while a /* comment */ can cross line boundaries.

To run this script, go to a command window, change to the same directory, and run the following command:

scala upper1-script.scala

The file is interpreted, meaning it is compiled and executed in one step. You should get the following output:


In the current example, the upper method in the Upper class (no pun intended) converts the input strings to uppercase and returns them in an array. The last line in the example converts four strings and prints the resulting Array.

Let’s examine the code in detail, so we can begin to learn Scala syntax. There are a lot of details in just six lines of code! We’ll explain the general ideas here. All the ideas used in this example will be explained more thoroughly in later sections of the book.

In the example, the Upper class begins with the class keyword. The class body is inside the outermost curly braces ({...}).

The upper method definition begins on the second line with the def keyword, followed by the method name and an argument list, the return type of the method, an equals sign (=), and then the method body.

The argument list in parentheses is actually a variable-length argument list of Strings, indicated by the String* type following the colon. That is, you can pass in as many comma-separated strings as you want (including an empty list). These strings are stored in a parameter named strings. Inside the method, strings is actually an Array.


When explicit type information for variables is written in the code, these type annotations follow the colon after the item name (i.e., Pascal-like syntax). Why doesn’t Scala follow Java conventions? Recall that type information is often inferred in Scala (unlike Java), meaning we don’t always show type annotations explicitly. Compared to Java’s type item convention, the item: type convention is easier for the compiler to analyze unambiguously when you omit the colon and the type annotation and just write item.

The method return type appears after the argument list. In this case, the return type is Seq[String], where Seq (“sequence”) is a particular kind of collection. It is a parameterized type (like a generic type in Java), parameterized here with String. Note that Scala uses square brackets ([...]) for parameterized types, whereas Java uses angle brackets (<...>).


Scala allows angle brackets to be used in method names, e.g., naming a “less than” method < is common. So, to avoid ambiguities, Scala uses square brackets instead for parameterized types. They can’t be used in method names. Allowing < and > in method names is why Scala doesn’t follow Java’s convention for angle brackets.

The body of the upper method comes after the equals sign (=). Why an equals sign? Why not just curly braces ({...}), like in Java? Because semicolons, function return types, method arguments lists, and even the curly braces are sometimes omitted, using an equals sign prevents several possible parsing ambiguities. Using an equals sign also reminds us that even functions are values in Scala, which is consistent with Scala’s support of functional programming, described in more detail in Chapter 8.

The method body calls the map method on the strings array, which takes a function literal as an argument. Function literals are “anonymous” functions. They are similar to lambdas, closures, blocks, or procs in other languages. In Java, you would have to use an anonymous inner class here that implements a method defined by an interface, etc.

In this case, we passed in the following function literal:

(s:String) => s.toUpperCase()

It takes an argument list with a single String argument named s. The body of the function literal is after the “arrow,” =>. It calls toUpperCase() on s. The result of this call is returned by the function literal. In Scala, the last expression in a function is the return value, although you can have return statements elsewhere, too. The return keyword is optional here and is rarely used, except when returning out of the middle of a block (e.g., in an if statement).


The value of the last expression is the default return value of a function. No return is required.

So, map passes each String in strings to the function literal and builds up a new collection with the results returned by the function literal.

To exercise the code, we create a new Upper instance and assign it to a variable named up. As in Java, C#, and similar languages, the syntax new Upper creates a new instance. The up variable is declared as a read-only “value” using the val keyword.

Finally, we call the upper method on a list of strings, and print out the result with Console.println(...), which is equivalent to Java’s System.out.println(...).

We can actually simplify our script even further. Consider this simplified version of the script:

// code-examples/IntroducingScala/upper2-script.scala

object Upper {
  def upper(strings: String*) =

println(Upper.upper("A", "First", "Scala", "Program"))

This code does exactly the same thing, but with a third fewer characters.

On the first line, Upper is now declared as an object, which is a singleton. We are declaring a class, but the Scala runtime will only ever create one instance of Upper. (You can’t write new Upper, for example.) Scala uses objects for situations where other languages would use “class-level” members, like statics in Java. We don’t really need more than one instance here, so a singleton is fine.


Why doesn’t Scala support statics? Since everything is an object in Scala, the object construct keeps this policy consistent. Java’s static methods and fields are not tied to an actual instance.

Note that this code is fully thread-safe. We don’t declare any variables that might cause thread-safety issues. The API methods we use are also thread-safe. Therefore, we don’t need multiple instances. A singleton object works fine.

The implementation of upper on the second line is also simpler. Scala can usually infer the return type of the method (but not the types of the method arguments), so we drop the explicit declaration. Also, because there is only one expression in the method body, we drop the braces and put the entire method definition on one line. The equals sign before the method body tells the compiler, as well as the human reader, where the method body begins.

We have also exploited a shorthand for the function literal. Previously we wrote it as follows:

(s:String) => s.toUpperCase()

We can shorten it to the following expression:


Because map takes one argument, a function, we can use the “placeholder” indicator _ instead of a named parameter. That is, the _ acts like an anonymous variable, to which each string will be assigned before toUpperCase is called. Note that the String type is inferred for us, too. As we will see, Scala uses _ as a “wildcard” in several contexts.

You can also use this shorthand syntax in some more complex function literals, as we will see in Chapter 3.

On the last line, using an object rather than a class simplifies the code. Instead of creating an instance with new Upper, we can just call the upper method on the Upper object directly (note how this looks like the syntax you would use when calling static methods in a Java class).

Finally, Scala automatically imports many methods for I/O, like println, so we don’t need to call Console.println(). We can just use println by itself. (See The Predef Object for details on the types and methods that are automatically imported or defined.)

Let’s do one last refactoring. Convert the script into a compiled, command-line tool:

// code-examples/IntroducingScala/upper3.scala

object Upper {
  def main(args: Array[String]) = {"%s ",_))

Now the upper method has been renamed main. Because Upper is an object, this main method works exactly like a static main method in a Java class. It is the entry point to the Upper application.


In Scala, main must be a method in an object. (In Java, main must be a static method in a class.) The command-line arguments for the application are passed to main in an array of strings, e.g., args: Array[String].

The first line inside the main method uses the same shorthand notation for map that we just examined:

The call to map returns a new collection. We iterate through it with foreach. We use a _ placeholder shortcut again in another function literal that we pass to foreach. In this case, each string in the collection is passed as an argument to printf:

...foreach(printf("%s ",_))

To be clear, these two uses of _ are completely independent of each other. Method chaining and function-literal shorthands, as in this example, can take some getting used to, but once you are comfortable with them, they yield very readable code with minimal use of temporary variables.

The last line in main adds a final line feed to the output.

This time, you must first compile the code to a JVM .class file using scalac:

scalac upper3.scala

You should now have a file named Upper.class, just as if you had just compiled a Java class.


You may have noticed that the compiler did not complain when the file was named upper3.scala and the object was named Upper. Unlike Java, the file name doesn’t have to match the name of the type with public scope. (We’ll explore the visibility rules in Visibility Rules.) In fact, unlike Java, you can have as many public types in a single file as you want. Furthermore, the directory location of a file doesn’t have to match the package declaration. However, you can certainly follow the Java conventions, if you want to.

Now, you can execute this command for any list of strings. Here is an example:

scala -cp . Upper Hello World!

The -cp . option adds the current directory to the search “class path.” You should get the following output:


Therefore, we have met the requirement that a programming language book must start with a “hello world” program.

The best content for your career. Discover unlimited learning on demand for around $1/day.