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
scala> 1 res31: Int = 1
With this knowledge, we can see that:
1 + 2
in reality is syntactic sugar for:
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_! don’t take arguments and therefore can be invoked without parentheses.
Note: the only identifiers that can be used as prefix operators are +, -, ! and ~
1 & 2 1.&(2)
Functions are also objects:
val f: Int => Int = _ * 2 f(2) f.apply(2)
In this case,
apply is a method of
case class Person(name: String, age: Int) Person("Peter", 20) Person.apply("Peter", 20)
apply is a method of the companion object of the case class.
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.