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
An extractor object is an object with an `unapply` method. Whereas the `apply` method is like a constructor which takes arguments and creates an object, the `unapply` takes an object and tries to give back the arguments. This is most often used in pattern matching and partial functions.
caseCustomerID(name) => println(name) // prints Sukyoung
54
+
case _ => println("Could not extract a CustomerID")
55
+
```
56
+
{% endtab %}
57
+
58
+
{% endtabs %}
34
59
35
60
The `apply` method creates a `CustomerID` string from a `name`. The `unapply` does the inverse to get the `name` back. When we call `CustomerID("Sukyoung")`, this is shorthand syntax for calling `CustomerID.apply("Sukyoung")`. When we call `case CustomerID(name) => println(name)`, we're calling the unapply method with `CustomerID.unapply(customer1ID)`.
36
61
37
62
Since a value definition can use a pattern to introduce a new variable, an extractor can be used to initialize the variable, where the unapply method supplies the value.
38
63
64
+
{% tabs extractor-objects_use-case-1 %}
65
+
66
+
{% tab 'Scala 2 and 3' for=extractor-objects_use-case-1 %}
39
67
```scala mdoc
40
68
valcustomer2ID=CustomerID("Nico")
41
69
valCustomerID(name) = customer2ID
42
70
println(name) // prints Nico
43
71
```
72
+
{% endtab %}
73
+
74
+
{% endtabs %}
44
75
45
76
This is equivalent to `val name = CustomerID.unapply(customer2ID).get`.
46
77
78
+
{% tabs extractor-objects_use-case-2 %}
79
+
80
+
{% tab 'Scala 2 and 3' for=extractor-objects_use-case-2 %}
47
81
```scala mdoc
48
82
valCustomerID(name2) ="--asdfasdfasdf"
49
83
```
84
+
{% endtab %}
85
+
86
+
{% endtabs %}
50
87
51
88
If there is no match, a `scala.MatchError` is thrown:
52
89
53
-
```scala
90
+
{% tabs extractor-objects_use-case-3 %}
91
+
92
+
{% tab 'Scala 2 and 3' for=extractor-objects_use-case-3 %}
93
+
```scala mdoc:crash
54
94
valCustomerID(name3) ="-asdfasdfasdf"
55
95
```
96
+
{% endtab %}
97
+
98
+
{% endtabs %}
56
99
57
100
The return type of an `unapply` should be chosen as follows:
0 commit comments