Scala problem: You want to define an
equals method for your class so you can compare object instances to each other.
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.
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).”
You need to cast an instance of a class from one type to another, such as when creating objects dynamically.
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:
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).”
In Scala, you want to write a block of code to match one type, or multiple different types.
You can use the
isInstanceOf method to test the type of an object:
I was doing a little Scala programming this morning, and because I hadn't written any code in a while, I managed to forget how isInstanceOf works with inheritance in Scala.
To refresh my memory, I wrote the following example code: