Scala, the better Java

one stop site for scala learners

Tag Archives: Scala

The better object equality support in scala compared to java

Scala is considered to be better than Java in various aspects when it comes to ease of programming. But, there are some group of programmers who still like to debate on various aspects of Scala. Now, i am going to show examples on how easily we can do the object equality test in Scala compared to Java.

In Scala, everything is an object. We can use == operator to check for object equality. Have a look at the below code samples,

You can also try these samples by starting the scala REPL[Read, Evaluate, Print, Loop] prompt.

scala> 5 == 5
res0: Boolean = true
scala> 5 == 8
res1: Boolean = false
scala> 6 != 0
res2: Boolean = true

The comparisons shown above are samples of regular application. Let us see more on this.

We can apply the object equality across the types, such as

scala> 1 == 1.0
res3: Boolean = true
scala> 2 == 2.0001
res4: Boolean = false

You can observe from the above 2 comparison that, object equality can be done on two entirely different object types.

Now, the things become more and more interesting as we start learning more and more about object equality support in Scala language. Look at the below code samples on Lists. It’s quite good to have such support built into the language itself.

scala> List("Martin Odersky", "Jonas Boner") == List("James Gosling", "Patrick Naughton")
res5: Boolean = false scala> List(1,2) == List(1,2)
res6: Boolean = true

One last set of samples on null references handled during object equality. THIS IS QUITE INTERESTING TO KNOW. FOLLOW ME.

scala> null == List(2,3)
res7: Boolean = false scala> List(2,3) == null
res8: Boolean = false

You can compare against Null, and NO EXCEPTION IS THROWN.

The == operator is carefully designed such that we can use it for most of our daily use cases as shown above.

It is done with a simple rule. First check the left-side for null. If is it not null, then call “equals” method on it. The behavior of equals method is entirely depending on the type of the left-hand side argument.

Since, there is an automatic null check, you don't have to do it on your own!!!
 
To know more about current happenings in Scala world, please visit the official site of scala programming, http://www.scala-lang.org/.