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
Copy file name to clipboardExpand all lines: _tour/case-classes.md
+32Lines changed: 32 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -15,36 +15,64 @@ Case classes are like regular classes with a few key differences which we will g
15
15
16
16
## Defining a case class
17
17
A minimal case class requires the keywords `case class`, an identifier, and a parameter list (which may be empty):
18
+
19
+
{% tabs case-classe_Book %}
20
+
21
+
{% tab 'Scala 2 and 3' for=case-classe_Book %}
18
22
```scala mdoc
19
23
caseclassBook(isbn: String)
20
24
21
25
valfrankenstein=Book("978-0486282114")
22
26
```
27
+
{% endtab %}
28
+
29
+
{% endtabs %}
30
+
23
31
Notice how the keyword `new` was not used to instantiate the `Book` case class. This is because case classes have an `apply` method by default which takes care of object construction.
24
32
25
33
When you create a case class with parameters, the parameters are public `val`s.
34
+
35
+
{% tabs case-classe_Message_define %}
36
+
37
+
{% tab 'Scala 2 and 3' for=case-classe_Message_define %}
26
38
```
27
39
case class Message(sender: String, recipient: String, body: String)
28
40
val message1 = Message("guillaume@quebec.ca", "jorge@catalonia.es", "Ça va ?")
29
41
30
42
println(message1.sender) // prints guillaume@quebec.ca
31
43
message1.sender = "travis@washington.us" // this line does not compile
32
44
```
45
+
{% endtab %}
46
+
47
+
{% endtabs %}
48
+
33
49
You can't reassign `message1.sender` because it is a `val` (i.e. immutable). It is possible to use `var`s in case classes but this is discouraged.
34
50
35
51
## Comparison
36
52
Instances of case classes are compared by structure and not by reference:
53
+
54
+
{% tabs case-classe_Message_compare %}
55
+
56
+
{% tab 'Scala 2 and 3' for=case-classe_Message_compare %}
0 commit comments