|
| 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