2. Values, methods and expressions

Before Fully Booked takes a booking, it has to be able to tell the customer what they’re agreeing to. Two things matter to them: how long they get the table for, and whether there’s a deposit to pay. This restaurant’s rules are:

  • A party of up to four has the table for 90 minutes. Bigger parties get two hours.

  • Parties of six or more pay a deposit of £10 a head.

We’ll turn those rules into a small program, quote.scala, writing it first the way a Java developer might on their first day with Scala and then improving it a step at a time. Most of Scala’s everyday syntax turns up along the way.

2.1. A method, written the Java way

Create quote.scala in your working directory:

//> using scala 3.9.0
//> using jvm 25

def stayMinutes(partySize: Int): Int =
  var minutes = 0
  if partySize <= 4 then
    minutes = 90
  else
    minutes = 120
  return minutes

@main def printQuote(partySize: Int): Unit =
  val minutes = stayMinutes(partySize)
  println(s"Party of $partySize: table for $minutes minutes")

Run it with --watch this time:

$ scala run quote.scala --watch -- 5
Party of 5: table for 120 minutes
Program exited with return code 0.
Watching sources, press Ctrl+C to exit, or press Enter to re-run.

With --watch the command doesn’t exit. Each time you save the file, it recompiles and runs the program again. That suits a chapter like this one, where the same file keeps changing. I’ll show plain scala run commands from here on. If you like the watcher, keep it going in a terminal of its own and restart it whenever the program’s arguments change.

stayMinutes sits at the top level of the file, as tables did in chapter 1. It’s correct, though I wrote it as Java with different punctuation, right down to the variable that exists only so that each branch has something to assign to.

Scala source has no split between int and Integer: you write Int everywhere. The compiler uses a primitive int wherever it can and boxes where it must, inside a List[Int] for instance. Long, Double and Boolean get the same treatment.

2.2. Everything has a value

In Java, if is a statement: it does things but doesn’t produce a result, which is why Java also has the ?: operator. A Scala if is an expression. It evaluates to the value of whichever branch was taken, so the result can be assigned directly:

def stayMinutes(partySize: Int): Int =
  val minutes = if partySize <= 4 then 90 else 120
  return minutes

Now minutes is a name for a value that gets used once, on the very next line. Drop it. Drop the return as well. A method’s result is the value of the last expression in its body:

def stayMinutes(partySize: Int): Int =
  if partySize <= 4 then 90 else 120

Save the file and run it again. It prints the same answer as before.

This is what Scala methods normally look like. You’ll rarely see return in one (the keyword exists, but it’s seldom needed when every if produces a value). You won’t see a ternary operator at all, since if with an else already is one.

Blocks follow the same rule: any indented run of lines is an expression, whose value is the value of its last line. That means a block can go anywhere a value can. Inside stayMinutes, for instance, you could write:

val minutes =
  val small = partySize <= 4
  if small then 90 else 120

small exists only inside the block. A block like this is a tidy way to stop a helper value leaking into the rest of a method.

If everything has a value then so does println("hello"). Its value is (), which is the only value of the type Unit and represents “nothing”. An if without an else produces () as well. Where void is a special case in Java’s grammar, Unit is an ordinary type, which is why printQuote can declare it as a return type like any other.

2.2.1. val or var?

Developers in both kinds of codebase from chapter 1 generally use val unless they have a reason not to. The argument is the one for final in Java: if a name can’t be reassigned, you never have to read the rest of a method to find out what it refers to further down. Few people write final on Java locals, probably because it’s extra typing. In Scala, val is no more typing than var.

A var can change its value but never its type:

scala> var booked = 0
var booked: Int = 0

scala> booked = booked + 2
booked: Int = 2

scala> booked = "two"
-- [E007] Type Mismatch Error: ---------------------------------------------------------------------
1 |booked = "two"
  |         ^^^^^
  |         Found:    ("two" : String)
  |         Required: Int
  |
  | longer explanation available when compiling with `-explain`
1 error found

A var that’s only used inside a single method, such as a running total in a loop, does no harm. The ones that cause trouble are var fields on objects that several threads can reach, for the same reasons as in Java. Either way, expect a reviewer to ask about any var.

2.3. Arrival times: using a Java library

A customer would sooner hear “until 21:30” than “120 minutes”, and for that the program has to do arithmetic on times. Scala has no date and time library of its own, and doesn’t need one, because java.time can be used directly. Try it in the REPL:

scala> import java.time.LocalTime

scala> val arrival = LocalTime.parse("19:30")
val arrival: LocalTime = 19:30

scala> arrival.plusMinutes(90)
val res0: LocalTime = 21:00

scala> arrival.isBefore(LocalTime.NOON)
val res1: Boolean = false

Apart from val and the missing semicolons, this is Java. Static methods and constants such as LocalTime.parse and LocalTime.NOON are used in the usual way. import can also take a whole package, with import java.time.*, or a few named classes, with import java.time.{LocalDate, LocalTime}.

Here’s the whole file with arrival times added. The time arrives as a string and is parsed inside printQuote, because @main can only convert simple types such as Int for you.

//> using scala 3.9.0
//> using jvm 25

import java.time.LocalTime

def stayMinutes(partySize: Int): Int =
  if partySize <= 4 then 90 else 120

@main def printQuote(partySize: Int, time: String): Unit =
  val arrival = LocalTime.parse(time)
  val leaveBy = arrival.plusMinutes(stayMinutes(partySize))
  println(s"Party of $partySize at $arrival: table until $leaveBy")

Run it:

$ scala run quote.scala -- 5 19:30
Party of 5 at 19:30: table until 21:30

Now give it a time that LocalTime.parse can’t read:

$ scala run quote.scala -- 5 7pm
Exception in thread "main" java.time.format.DateTimeParseException: Text '7pm' could not be parsed at index 0
	at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2108)
	at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:2010)
	at java.base/java.time.LocalTime.parse(LocalTime.java:475)
	at java.base/java.time.LocalTime.parse(LocalTime.java:460)
	at quote$package$.printQuote(quote.scala:10)
	at printQuote.main(quote.scala:9)

That’s an ordinary Java exception, with our own file in the bottom two frames of the trace. Scala has try, catch and finally to deal with one (a try is an expression, just as an if is). It doesn’t have checked exceptions. LocalTime.parse happens to throw an unchecked one, but you can equally call a Java method that declares throws IOException without writing a try or a throws clause of your own. That’s convenient until something throws that you weren’t expecting, since the compiler won’t have warned you. Chapter 9 shows how the functional style deals with this, by handing a foreseeable failure such as bad input back as a value.

2.4. Leaving types out, and putting them in

val arrival = LocalTime.parse(time) doesn’t say what type arrival is. The compiler inferred it, as it did in the REPL. Method parameters never get that treatment: their types must always be written out. Return types are in between: the compiler can infer them, but you’re allowed to state them. stayMinutes would compile without its : Int.

I’d keep it, and the quickest way to show why is to make a mistake on purpose. Delete the return type from stayMinutes (the : Int after the parameter list), then put quotation marks around the 120 to turn it into a string:

$ scala run quote.scala -- 5 19:30
[error] ./quote.scala:11:37
[error] Found:    Int | String
[error] Required: Long
[error]   val leaveBy = arrival.plusMinutes(stayMinutes(partySize))
[error]                                     ^^^^^^^^^^^^^^^^^^^^^^
Compilation failed

The compiler reports the error on line 11, in printQuote, at the call to stayMinutes. The mistake is on line 7. The message says it found an Int | String, which is how Scala writes a type that’s either an Int or a String. With no return type declared, the compiler decided that a method returning a number from one branch and a string from the other must be what you wanted. It only objected when plusMinutes, which takes a Long, was handed something that could be a String. In a real codebase that call could be in another file, written by somebody else.

Put the : Int back and leave the quotation marks in:

$ scala run quote.scala -- 5 19:30
[error] ./quote.scala:7:34
[error] Found:    ("120" : String)
[error] Required: Int
[error]   if partySize <= 4 then 90 else "120"
[error]                                  ^^^^^
Compilation failed

The rule I follow is to let the compiler infer the types of local values and to declare the return type of every method that isn’t a tiny private helper. The official Scala style guide asks for the same on all public methods. Besides putting errors in the right place, a declared type lets a reader see what a method returns without reading its body.

Take the quotation marks out again before going on.

2.5. Deposits: money and operators

The second rule involves money. Don’t keep it in a Double, which goes wrong in Scala exactly as it does in Java:

scala> 0.1 + 0.2
val res0: Double = 0.30000000000000004

scala> BigDecimal("0.10") + BigDecimal("0.20")
val res1: BigDecimal = 0.30

scala> BigDecimal("10.00") * 7
val res2: BigDecimal = 70.00

scala> BigDecimal("10.00").*(7)
val res3: BigDecimal = 70.00

The right type is BigDecimal, as it would be in Java, except that this is Scala’s own BigDecimal, a thin wrapper around java.math.BigDecimal whose main purpose is to let you add and multiply with + and *. If you’ve ever written price.multiply(quantity).add(delivery), you’ll see the appeal.

The * in that session is a method on BigDecimal that happens to have a symbol for a name. The last line of the session calls it the long way round, as BigDecimal("10.00").*(7). All of Scala’s operators work like this, including the ones on numbers: 2 + 3 is a call to a method named + on Int, though the compiler turns it into the same bytecode as Java’s addition.

Library authors sometimes get carried away with this. You’ll meet methods called <+> and *>, which you can neither pronounce nor type into a search engine. Good Scala code keeps symbols for things that are operators everywhere else, mostly arithmetic, and gives everything else a name. Where a later chapter needs one of the odd ones, I’ll tell you how to say it.

Here’s the deposit rule. Add it under stayMinutes:

def deposit(partySize: Int, perHead: BigDecimal = BigDecimal("10.00")): BigDecimal =
  if partySize >= 6 then perHead * partySize else BigDecimal(0)

perHead has a default value, so a call can leave it out. Load the file into the REPL with scala repl quote.scala and call the method a few different ways:

scala> deposit(8)
val res0: BigDecimal = 80.00

scala> deposit(8, BigDecimal("15.00"))
val res1: BigDecimal = 120.00

scala> deposit(perHead = BigDecimal("15.00"), partySize = 8)
val res2: BigDecimal = 120.00

scala> deposit(4)
val res3: BigDecimal = 0

Arguments can also be passed by name, in any order, which is what the call with perHead first is doing. Naming is most useful when a call would otherwise be a row of bare literals. deposit(8, BigDecimal("15.00")) is clear enough, but a reader of resize(800, 600, true, false) can’t tell what the two Booleans mean. Java has neither default nor named arguments, and that’s where its chains of overloads and its builder classes come from.

Now use deposit in printQuote:

@main def printQuote(partySize: Int, time: String): Unit =
  val arrival = LocalTime.parse(time)
  val leaveBy = arrival.plusMinutes(stayMinutes(partySize))
  val due = deposit(partySize)
  println(s"Party of $partySize at $arrival: table until $leaveBy, deposit $due")
$ scala run quote.scala -- 7 19:30
Party of 7 at 19:30: table until 21:30, deposit 70.00
$ scala run quote.scala -- 2 19:30
Party of 2 at 19:30: table until 21:00, deposit 0

The sums are right. The presentation needs work: there’s no pound sign, and “deposit 0” isn’t something to show a customer. Fixing it means testing whether a BigDecimal is zero, so I want to look at how Scala compares things first.

2.6. == means equals

Java developers learn early not to compare objects with ==. In Scala that’s how you’re meant to compare them:

scala> val a = new String("table")
val a: String = "table"

scala> val b = new String("table")
val b: String = "table"

scala> a == b
val res0: Boolean = true

scala> a eq b
val res1: Boolean = false

scala> BigDecimal("10.0") == BigDecimal("10.00")
val res2: Boolean = true

scala> new java.math.BigDecimal("10.0").equals(new java.math.BigDecimal("10.00"))
val res3: Boolean = false

scala> BigDecimal("70.00") == 70
val res4: Boolean = true

In Scala, == calls equals, so a and b are equal even though they’re separate objects. I used new, which Scala still accepts, to make sure of that. The old Java bug of comparing strings with == can’t be written. Reference comparison is still available as eq, a method that’s written between its operands the way == is, for the rare occasions when you want it.

Java’s BigDecimal.equals compares the scale as well as the value, making 10.0 and 10.00 unequal, and plenty of Java developers have been caught out by that. Scala’s wrapper compares by value alone. It even compares a BigDecimal with an Int sensibly. Comparing the deposit with 0 is all the zero test we need.

2.7. Tidying the output

printQuote is getting long, and working out a quote is a different job from printing one. I want a method that works the quote out and hands it back, which means returning two values, the leaving time and the deposit. In Java you’d write a small record to carry them. For a case this small, Scala has something lighter called a tuple:

scala> val pair = (90, "no deposit")
val pair: (Int, String) = (90, "no deposit")

scala> pair._1
val res0: Int = 90

scala> val (minutes, text) = pair
val minutes: Int = 90
val text: String = "no deposit"

scala> val named = (minutes = 90, text = "no deposit")
val named: (minutes : Int, text : String) = (90, "no deposit")

scala> named.text
val res1: String = "no deposit"

A tuple is a fixed number of values grouped together, each with its own type. (Int, String) is the type of a pair holding an Int followed by a String. You can get at the parts by position with ._1 and ._2, but that reads badly. Taking the whole tuple apart in one go, the way val (minutes, text) = pair does, is better.

named is a named tuple, where each part has a name as well as a position. Named tuples only arrived in Scala 3.7, so you won’t find them in codebases that are still on the previous LTS, 3.3.

Replace printQuote with these three methods:

def quote(partySize: Int, arrival: LocalTime): (leaveBy: LocalTime, deposit: BigDecimal) =
  val leaveBy = arrival.plusMinutes(stayMinutes(partySize))
  (leaveBy, deposit(partySize))

def describe(partySize: Int, arrival: LocalTime): String =
  val q = quote(partySize, arrival)
  val depositText =
    if q.deposit == 0 then "no deposit" else f"deposit £${q.deposit}%.2f"
  s"Party of $partySize at $arrival: table until ${q.leaveBy}, $depositText"

@main def printQuote(partySize: Int, time: String): Unit =
  println(describe(partySize, LocalTime.parse(time)))
$ scala run quote.scala -- 7 19:30
Party of 7 at 19:30: table until 21:30, deposit £70.00
$ scala run quote.scala -- 2 12:15
Party of 2 at 12:15: table until 13:45, no deposit

quote returns its two results as a named tuple, written as an ordinary pair in parentheses on its last line. describe reads them back out by name.

The one new piece of syntax is the f in front of the deposit string. An f string is an s string that also accepts printf formats after each value. Here %.2f prints the deposit to two decimal places.

Keep tuples for passing a couple of values from one method to the next inside a file. Once a group of values starts travelling around a codebase, or grows a third and fourth member, it should be a case class. Chapter 3 starts with those.

2.8. Every party size at once

It would be easier to check the rules if we could see quotes for a whole range of party sizes together. Replace printQuote with printQuotes, which takes only the time:

@main def printQuotes(time: String): Unit =
  val arrival = LocalTime.parse(time)
  for partySize <- 1 to 8 do
    println(describe(partySize, arrival))
$ scala run quote.scala -- 19:30
Party of 1 at 19:30: table until 21:00, no deposit
Party of 2 at 19:30: table until 21:00, no deposit
Party of 3 at 19:30: table until 21:00, no deposit
Party of 4 at 19:30: table until 21:00, no deposit
Party of 5 at 19:30: table until 21:30, no deposit
Party of 6 at 19:30: table until 21:30, deposit £60.00
Party of 7 at 19:30: table until 21:30, deposit £70.00
Party of 8 at 19:30: table until 21:30, deposit £80.00

The loop runs its body once for each number from 1 to 8 inclusive. Read the <- as “taken from”. This is the only kind of for in Scala, which has never had the for (int i = 0; i < n; i++) form. 1 to 8 builds a range, and since operators are methods you might guess that to is an ordinary method being called on 1. It is: 1 to 8 means 1.to(8). Write 1 until 8 if you want to stop at 7. Scala has while loops as well, without the do/while form and without break or continue keywords.

You’ll probably write fewer loops in Scala than you do in Java. Most of the jobs a Java for loop does are done by methods on collections, like the filter and minBy in chapter 1.

2.9. Indentation, braces and end

By now you’ve seen a fair amount of code in which indentation decides what belongs to what. If whitespace in Python or YAML has ever bitten you, you’ll want to know how far to trust it here.

The compiler is strict about indentation that doesn’t line up with anything. Here’s a version of stayMinutes with the else one space too far in, in a file I’ve called stay.scala, and what the compiler makes of it:

def stayMinutes(partySize: Int): Int =
  if partySize <= 4 then
    90
   else
    120
$ scala compile stay.scala
[error] ./stay.scala:4:4
[error] The start of this line does not match any of the previous indentation widths.
[error] Indentation width of current line : 3 spaces
[error] This falls between previous widths: 2 spaces and 4 spaces
[error]    else
[error]    ^
Compilation failed

scala compile builds a file without running it. A line that’s indented consistently but at the wrong level gets past any compiler, as in this second throwaway file, deposit.scala:

@main def askForDeposit(due: Int): Unit =
  if due > 0 then
    println("Deposit required")
  println("Card details needed")

The second println was supposed to be inside the if. It isn’t, so it runs for a customer who owes nothing:

$ scala run deposit.scala -- 0
Card details needed

Java has the same trap when an if is written without braces. I’d rate the risk about the same: low, because the mistake is at least visible on the screen, though it still gets through review now and then.

When a body is long enough that its first line has scrolled off the screen, you can mark where it finishes with end:

def stayMinutes(partySize: Int): Int =
  if partySize <= 4 then
    90
  else
    120
  end if
end stayMinutes

end markers are optional but checked: an end stayMinutes that closes something other than stayMinutes is a compile error. I’d put them on anything longer than a screen.

Braces remain legal everywhere, as you saw in chapter 1, and plenty of teams use them, particularly teams whose code began in Scala 2. Go with whatever the codebase in front of you already does. A team that changes its mind can have the compiler do the conversion. Put //> using options -rewrite -no-indent at the top of a file like ours and compile it once, and the compiler rewrites the file with braces. -rewrite -indent takes them out again.

Indent with two spaces. Scalafmt, the standard formatter, does the same, and so does every Scala codebase you’re likely to meet.

2.10. Exercises

Solutions are in the book’s downloadable code, under ch02/exercises.

  1. Lunch is quicker. Any party arriving before 15:00 gets 75 minutes, whatever its size. stayMinutes will need the arrival time as a second parameter. LocalTime.of(15, 0) gives you the cut-off, and conditions can be chained with else if.

  2. The owner decides that no deposit should be more than £100. BigDecimal has a min method. Check your change in the REPL with deposit(14).

  3. The kitchen takes bookings from noon until 21:30. Write kitchenOpen(arrival: LocalTime): Boolean, then make describe return a different message when the kitchen is closed.

  4. Predict the value and the type of each of these, then check in the REPL: "8" + 8, 8 / 3 * 3.0, BigDecimal("1.10") == BigDecimal("1.1") and (1, "a") == (1, "a").

  5. With quote.scala loaded in the REPL, work out the deposit for a party of 6 at £12.50 a head. Pass the arguments in the opposite order to the one in which deposit declares them.