
172
CHAPTER 7 
■  TRAITS AND TYPES AND GNARLY STUFF FOR ARCHITECTS
Scala is unique among the languages I’ve used in that it gives a different set of tools and 
powers to different team members. Scala’s traits, type system, flexible syntax, and implicit 
conversions give amazingly powerful tools to architects and library designers to build 
libraries that are simultaneously easy and safe to use. Safety means that tests can focus on 
the logic of code, not calling conventions. We’ve seen some examples of the safety of 
using 
Option instead of null testing. Being able to reason about the safety by making sure 
that things have the correct types is very powerful. It also means that the library consumers 
can focus on their business logic without worrying about declaring lots of fancy types or 
other distractions. Library consumers don’t have to program defensively, because they 
can trust the correctness of parameters and of return values.
This chapter is a deep dive into the language features that make Scala different from 
Java. These are tools that I use when I design code bases for other people to consume. 
These tools let me write code that I can reason is correct, so when I go to write application 
code, I can be sure that my code is correct if my logic is correct. I can write logic-oriented 
tests rather than tests that try to fool my code and make sure that I’m guarding against 
nulls or other parameter and type-related problems.
1
Show Me Some Bad Java Code
So, I’ve talked about Java code not being as type-safe as Scala code. You’re probably 
thinking, “But Java is a statically typed language, doesn’t it give me all the safety that Scala 
does?” The answer to that is no. Take a look at the following code and spot the problem:
public class Bad {
  public static void main(String[] argv) {
    Object[] a = argv;
    a[0] = new Object();
  }
}
This is legal Java code, and here’s what happens when we run the code:
> java Bad Hello
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Object
        at Bad.main(Bad.java:4)
1. Among enthusiasts of other statically typed languages with rich type systems (Standard ML, Haskell, 
OCaml) the “architect style” is often referred to as “typeful programming,” referring exactly to this 
distinction between “going with the type inference flow” and “using the type system deliberately to 
encode important invariants.”
19897ch07.fm  Page 172  Monday, April 20, 2009  4:36 PM