Skip to content

Commit 3bcecc9

Browse files
author
artem.kupchinskiy
committed
[SCALA-26] First draft
1 parent cdcdd3c commit 3bcecc9

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.baeldung.scala
2+
3+
package object equality {
4+
5+
// A class with default equals/hashcode implementations
6+
class PersonFirst(val name: String, val age: Int)
7+
8+
// A class with overridden equals/hashcode implementations
9+
class PersonSecond(val name: String, val age: Int) {
10+
override def equals(other: Any): Boolean = other match {
11+
case person: PersonSecond =>
12+
this.name == person.name && this.age == person.age
13+
case _ => false
14+
}
15+
16+
override def hashCode(): Int = if (name eq null) age else name.hashCode + 31 * age
17+
}
18+
19+
// A case class with the compiler-generated equals/hashcode implementations
20+
case class PersonThird(name: String, age: Int)
21+
22+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.baeldung.scala.equality
2+
3+
import org.scalatest.FlatSpec
4+
5+
class EqualityTest extends FlatSpec {
6+
"Equality operator for AnyVal" should "work as in Java" in {
7+
val intAnyVal = 4
8+
val booleanAnyVal = false
9+
assert(intAnyVal == 2 * 2)
10+
assert((intAnyVal > 10) == booleanAnyVal)
11+
}
12+
13+
"Equality operator for referential types" should "work like null-safe equals()" in {
14+
val str1 = new String("AnyRef")
15+
val str2 = new String("AnyRef")
16+
val str3 = null
17+
val str4 = null
18+
assert(str1 == str2)
19+
// Unlike in java, the following lines of code do not cause NullPointerExceptions
20+
assert(str3 != str2)
21+
assert(str4 == str3)
22+
}
23+
24+
"Equals()" should "work as in Java" in {
25+
val str1 = new String("AnyRef")
26+
val str2 = new String("AnyRef")
27+
val str3 = null
28+
assert(str1.equals(str2))
29+
assertThrows[NullPointerException](str3.equals(str2))
30+
}
31+
32+
"Eq and ne" should "check referential equality" in {
33+
val str1 = new String("AnyRef")
34+
val str2 = new String("AnyRef")
35+
val str3 = str2
36+
assert(str1 ne str2)
37+
assert(str3 eq str2)
38+
// Both operators are null-safe
39+
assert(null eq null)
40+
assert(null ne str1)
41+
}
42+
43+
"Equality operator" should "not work out of the box for PersonFirst" in {
44+
val pf1 = new PersonFirst("Donald", 66)
45+
val pf2 = new PersonFirst("Donald", 66)
46+
assert(pf1 != pf2)
47+
}
48+
49+
"Equality operator" should "work for PersonSecond and PersonThird" in {
50+
val ps1 = new PersonSecond("Donald", 66)
51+
val ps2 = new PersonSecond("Donald", 66)
52+
val pt1 = PersonThird("Donald", 66)
53+
val pt2 = PersonThird("Donald", 66)
54+
assert(ps1 == ps2)
55+
assert(pt1 == pt2)
56+
// There is no duck-typing though
57+
assert(ps1 != pt1)
58+
}
59+
}

0 commit comments

Comments
 (0)