Operators are methods

An operator in Scala is a method. 1 + 2 and 1.+(2) are the same call, the first form is only the spelling a reader expects, and a class can define its own operator without any keyword. The rule is about the name: a method whose name is a sequence of symbols is called with infix syntax.

The call behind the operator

The program below writes both forms of the same three operations. The list operator :: puts an element in front of a list and ::: joins two of them; the unary minus applies to a parenthesised number, and ! is a method of Boolean:

operators.scala

@main def operators(): Unit = println(1 + 2) println(1.+(2)) println(2 :: List(3)) println(List(1) ::: List(2, 3)) println((-5).abs) println(!true) println(1 + 2 * 3) println((1 + 2) * 3)

scala-cli run --server=false operators.scala

3
3
List(2, 3)
List(1, 2, 3)
5
false
7
9

(-5).abs needs the parentheses: without them the compiler reads the minus as part of the literal -5 and warns about an ambiguous literal, which is a real message of this compiler rather than a style rule.

Precedence comes from the first character

Scala has no operator table. The precedence of an operator is decided by its first character, in this order from loosest to tightest:

So 1 + 2 * 3 is 7 for the same reason as in Java, and an operator that ends in a colon groups to the right: a :: b :: Nil is a :: (b :: Nil). A method that ends in a colon is called on the value on the right, which is why 2 :: List(3) works: the list is the receiver.

Assignment operators are methods too. count += 1 is count = count + 1 for a var, and a class that defines += keeps the name it defines.

A custom operator

A case class with a + and a * reads like the arithmetic it models. The operator is an ordinary method with a symbolic name, and the precedence still follows the first character, so + binds looser than *:

custom.scala

case class Duration(seconds: Int): def +(other: Duration): Duration = Duration(seconds + other.seconds) def *(factor: Int): Duration = Duration(seconds * factor) @main def custom(): Unit = val short = Duration(30) val long = Duration(90) println(short + long) println(short * 3) println(short + long * 2)

scala-cli run --server=false custom.scala

Duration(120)
Duration(90)
Duration(210)

The third line is short + (long * 2) because * binds tighter, and the result is 210 seconds. An operator nobody can read is a worse name than a method; the ones worth defining are the ones the type already suggests, as + does for a duration.

Related

Article author: Arthur Isaev