Scala’s uniform object model

Scala is functional and object-oriented. In a way, Scala is more object-oriented than Java as it has a uniform object model similar to Smalltalk’s.

So what is this uniform object model? In a nutshell: every value is an object and every operation is a method call.

That’s right, there are no primitive types, i.e. 1 is an object of type Int

scala> 1
res31: Int = 1

With this knowledge, we can see that:

1 + 2

in reality is syntactic sugar for:

1.+(2)

The same syntactic sugar that allows to use any method like it was an operator:

"abcd" drop 2

Here’s a few more examples:

Unary operators

-2
2.unary_-
!true
true.unary_!

The methods unary_- and unary_! don’t take arguments and therefore can be invoked without parentheses.

Note: the only identifiers that can be used as prefix operators are +, -, ! and ~

Bitwise operators

1 & 2
1.&(2)

Functions

Functions are also objects:

val f: Int => Int = _ * 2
f(2)
f.apply(2)

In this case, apply is a method of Function1[Int, Int]

Case classes

case class Person(name: String, age: Int)
Person("Peter", 20)
Person.apply("Peter", 20)

Here apply is a method of the companion object of the case class.

Collections

List("x", "y")
List.apply("x", "y")
scala> val arr = new Array[Int](3)
arr: Array[Int] = Array(0, 0, 0)

scala> arr(0) = 1

scala> arr
res1: Array[Int] = Array(1, 0, 0)

scala> arr.update(0,2)

scala> arr
res3: Array[Int] = Array(2, 0, 0)

I hope that these examples about the uniformity of Scala’s object model will help beginners understand Scala patterns and constructs.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.