isinstanceof

How to define an `equals` method in a Scala class (object equality)

Table of Contents1 - Solution2 - A Scala `equals` method example3 - Discussion4 - Example 2: A Scala `equals` method with inheritance5 - Implementing hashCode6 - See Also

Scala problem: You want to define an equals method for your class so you can compare object instances to each other.

Back to top

Solution

If you’re new to Scala, a first thing to know is that object instances are compared with ==:

"foo" == "foo"   // true
"foo" == "bar"   // false
"foo" == null    // false
null == "foo"    // false
1 == 1           // true
1 == 2           // false
1d == 1.0d       // true

case class Person(name: String)
Person("Jess") == Person("Jessie")   // false

This is different than Java, which uses == for primitive values and equals for object comparisons.

How to cast a Scala object from one type to another (object casting)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 6.1, “How to cast an object from one type to another (object casting).”

Problem

You need to cast an instance of a class from one type to another, such as when creating objects dynamically.

Solution

Use the asInstanceOf method to cast an instance to the desired type. In the following example, the object returned by the lookup method is cast to an instance of a class named Recognizer:

How to use a Scala match expression instead of isInstanceOf (to match types)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a short recipe, Recipe 3.14, “How to use a match expression instead of isInstanceOf (to match types).”

Problem

In Scala, you want to write a block of code to match one type, or multiple different types.

Solution

You can use the isInstanceOf method to test the type of an object: