You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
While it works, it's tedious to define those methods for all classes you want to compare by value.
168
-
169
-
Thankfully, Scala has another type of class called `case class` that's compared by value by default.
155
+
Scala has a special type of class called case class that's immutable by default and compared by value. You can define case classes with the `case class` keywo
10000
rd.
170
156
171
157
```
172
158
case class Point(x: Int, y: Int)
@@ -175,28 +161,26 @@ case class Point(x: Int, y: Int)
175
161
You can instantiate case classes without `new` keyword.
176
162
177
163
```
178
-
val point = Point(1, 2) // no "new" here
164
+
val point = Point(1, 2)
179
165
val anotherPoint = Point(1, 2)
180
166
val yetAnotherPoint = Point(2, 2)
181
-
println(point == anotherPoint) // true
182
-
println(point == yetAnotherPoint) // false
183
-
```
184
-
185
-
Case classes are immutable by default, but it also provides `copy` method so that you can easily create another instance of the class while reusing the values from exiting instances.
186
167
187
-
Using `copy` method, you can also write the above code like below.
168
+
if (point == anotherPoint) {
169
+
println(point + " and " + anotherPoint + " are the same.")
170
+
} else {
171
+
println(point + " and " + anotherPoint + " are different.")
172
+
}
173
+
// Point(1,2) and Point(1,2) are the same.
188
174
175
+
if (point == yetAnotherPoint) {
176
+
println(point + " and " + yetAnotherPoint + " are the same.")
177
+
} else {
178
+
println(point + " and " + yetAnotherPoint + " are different.")
179
+
}
180
+
// Point(1,2) and Point(2,2) are different.
189
181
```
190
-
val point = Point(1, 2)
191
-
val anotherPoint = point.copy()
192
-
val yetAnotherPoint = point.copy(x = 2)
193
-
println(point == anotherPoint) // true
194
-
println(point == yetAnotherPoint) // false
195
-
```
196
-
197
-
Because of case classes, you almost never see classes overriding `equals` and `hashCode` methods in Scala.
198
182
199
-
There are many other features you get out-of-the-box by using case classes. We will cover them in depth [later](case-classes.md).
183
+
There is a lot more to case classes that we'd like to introduce, and we are convinced you will fall in love with it! We will cover them in depth [later](case-classes.md).
0 commit comments