Chapter 3. Rounding Out the Basics

Let’s finish our survey of essential basics in Scala.

Defining Operators

Almost all operators are actually methods. Consider this most basic of examples:

1 + 2

The plus sign between the numbers is a method on the Int type.

Scala doesn’t have special primitives for numbers and Booleans that are distinct from types you define. They are regular types: Float, Double, Int, Long, Short, Byte, Char, and Boolean. Hence, they can have methods.

Therefore, + is actually a method implemented by Int. We can write 1.+(2), although it looks strange.

Fortunately, Scala also supports infix operator notation. When a method takes one argument and the name uses only nonalphanumeric characters, we can drop the period and parentheses to write the expression we want, 1 + 2.

This is infix notation because + is between the object and argument. It is also called operator notation because it is especially popular when writing libraries where mathematics operator notation is convenient.

Caution

Actually, they don’t always behave identically, due to operator precedence rules. While 1 + 2 * 3 = 7, 1.+(2)*3 = 9. When present, the period binds before the star.

Recall in “Tuples”, we used x -> y to create a tuple (x, y). This is also implemented as a method using a special library utility type called ArrowAssoc, defined in Predef. We’ll explore this type in “Extension Methods”.

Infix operator notation isn’t limited to methods that look like operators, meaning their names don’t ...

Get Programming Scala, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.