forked from DANS-KNAW/course-scala
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcase classes.sc
64 lines (57 loc) · 1.65 KB
/
case classes.sc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
- public fields `i` and `s`
- a constructor with arguments `i` and `s`
- a companion object with `apply` (and some other methods)
- no need for `new` keyword (because of the previous)
- pattern-match capability
- a getter for `i` and `s`
- overrides `equals`, `hashCode` and `toString` methods based on the constructor parameters
*/
case class Foo(i: Int, s: String)
/*
- public fields `i` and `s`
- a constructor with arguments `i` and `s`
- a companion object with `apply` (and some other methods)
- no need for `new` keyword (because of the previous)
- pattern-match capability
- a getter for `i` and `s`
- a setter for `s`
- overrides `equals`, `hashCode` and `toString` methods based on the constructor parameters
*/
case class Bar(i: Int, var s: String)
/*
- Same as `Bar`
- with default value for `s`
*/
case class Foobar(i: Int, var s: String = "")
/*
- private fields `i` and `s`
- public fields `isEven` and `stringLength`
- a constructor with arguments `i` and `s`
- a companion object with `apply` (and some other methods)
- no need for `new` keyword (because of the previous)
- pattern-match capability
- a getter for `isEven` and `stringLength`
- overrides `equals`, `hashCode` and `toString` methods based on the constructor parameters
*/
case class Baz(private val i: Int, private val s: String) {
val isEven = i % 2 == 0
val stringLength = s.length
}
val foo = Foo(1, "abc")
foo.i
foo.s
val bar = Bar(2, "def")
bar.i
bar.s
bar.s = "abc"
bar.s
val foobar = Foobar(2)
foobar.i
foobar.s
foobar.s = "abc"
foobar.s
val baz = Baz(3, "ghi")
// can't access the constructor fields
baz.isEven
baz.stringLength