Small steps to Scala (9/20) - operators

Scala
9/20

Operators

  • identifiers
  • inflix operators
  • unary operators
  • assignment operators
  • apply && update

Identifiers

The names of variables, functions, classes are collectively known as identifiers. Almost any sequence of ASCII characters are allowed as identifiers. The variable below is a valid function. It will return the square root of the argument.

val 根 = scala.math.sqrt _

println(根(20))

The above statement will print 4.47213595499958. This is very good for creating DSL or Domain Specific Language

Inflix operators

Inflix operators are identifiers who denote a method between two parameters of the form a identifier b, for example

1 to 10
1 -> 10

Unary operators

Unary operators are those identifiers who operate on only one parameter in the form of a identifier, for example:

1 toString

Assignment operators

The assignment operator is in the form of operator=, as shown below:

a operator= b
a = a operator b

a += b
a += a + b

Apply && update

In Scala, the function

f(arg1, arg2, ...)

is the short form of

f.apply(arg1, arg2, ...)

If the format is

f(arg1, arg2, ...) = value

this is short for

f.update(arg1, arg2, ..., value)

Let's see an example:

val price = new scala.collection.mutable.HashMap[String, Double]
price("coffee") = 13.7    // price of coffee is 13.7

price.update("coffee", 10.2) // price of coffee became 10.2
price.apply("coffee")   // return the latest price of coffee

[+] Scala series
  • Small steps to Scala 1/20 - the basics
  • Small steps to Scala 2/20 - functions
  • Small steps to Scala 3/20 - arrays
  • Small steps to Scala 4/20 - maps and tuples
  • Small steps to Scala 5/20- classes
  • Small steps to Scala 6/20 - objects
  • Small steps to Scala 7/20 - inheritance
  • Small steps to Scala 8/20 - files and regex

  • Disclaimer: This is by no means an original work it is merely meant to serve as a compilation of thoughts, code snippets and teachings from different sources.