== eq equals In Scala

Recent day when I was coding and a problem was encountered. After the screening, I find that there is something different between Java and Scala to judge object equality.

中文版

一、Java

There are two ways to judge object equality.

1、==

  • Basic Data Types: byte、short、int、long、float、double、boolean、char. They are judging an object’s value.
  • Reference Data Type: They are judging the object’s reference.

2、equals

Object class has defined equals method, the source code is below:

1
2
3
public boolean equals(Object obj) {
return (this == obj);
}

Default they judging object’s reference. But is unuseful for real project logic. So mostly we overwrite equals to judge an object’s value.
Most time when two objects have the same value, we think about they are equal. The string has overwritten equals method.

3、Common uses

Basically we always code like below when we want judging two object are equality.

1
if(str != null && str.equals("test"))

Or

1
if("test".equals(str))

Avoid str is null, occur NullPointException.

二、Scala

There are three methods in Scala, here are the official API defined:

  • final def eq(arg0: AnyRef): Boolean
    Tests whether the argument (that) is a reference to the receiver object (this).
  • def equals(arg0: Any): Boolean
    The equality method for reference types.
  • final def ==(arg0: Any): Boolean
    The expression x == that is equivalent to if (x eq null) that eq null else x.equals(that).

1、eq

In Scala, eq is judging object’s reference, is the same meaning of == in Java.

2、equals

equals have the same function as Java. Judging an object’s value.

3、==

First judging object whether is null, then return equals to judging object’s value, avoid NullPointException.

三、Summary

== in Java is the same meaning of eq in Scala.
equals in Java is the same meaning of equals in Java.
== in Scala first judging whether null then judging the value. Looks like an upgrade judging equally function.


# Scala

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×