BalaB
BalaB

Reputation: 3871

What is == mechanism in Scala?

Just would like to get some detail on how scala == works when comparing two strings.

How does object comaparision works in scala?

Upvotes: 0

Views: 113

Answers (3)

ka4eli
ka4eli

Reputation: 5424

In Scala everything is an object, as @avik mentioned == internally uses equals which is already defined for String class. If you want to properly use == for your own class - override equals. If you want to compare references - use eq. From docs:

The expression x == that is equivalent to

if (x eq null) that eq null else x.equals(that)

Upvotes: 0

avik
avik

Reputation: 2708

Just to build on Gizmo's answer, whilst == in Java or C# is an operator that checks for reference equality, in Scala it is a method that checks for value equality. == should be used when you want to check whether two Strings (or any two values in general) have the same value.

== is declared on the Any supertype as a final method. Internally it uses the equals method, also declared in Any but as a non-final method. When you want to change how == behaves for a type, you do this by overriding equals:

override def equals(that: Any) : Boolean = {
  ...
}

// You probably would want to override this too
override def hashCode = ...

Upvotes: 1

gizmo
gizmo

Reputation: 11909

== in Scala is equivalent to .equals() in Java

Upvotes: 2

Related Questions