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
@@ -21,26 +21,26 @@ object Extractors extends FlatSpec with Matchers with org.scalaexercises.definit
21
21
* val x = Twice(21)
22
22
* x match { case Twice(n) => Console.println(n) } // prints 21
23
23
* }
24
-
*
24
+
* }}}
25
25
*
26
26
* There are two syntactic conventions at work here:
27
27
*
28
-
* * The pattern `case Twice(n)` will cause an invocation of `Twice.unapply`, which is used to match even number; the return value of the `unapply` signals whether the argument has matched or not, and any sub-values that can be used for further matching. Here, the sub-value is `z/2`
29
-
* * The `apply` method is not necessary for pattern matching. It is only used to mimick a constructor. `val x = Twice(21)` expands to `val x = Twice.apply(21)`.
28
+
* - The pattern `case Twice(n)` will cause an invocation of `Twice.unapply`, which is used to match even number; the return value of the `unapply` signals whether the argument has matched or not, and any sub-values that can be used for further matching. Here, the sub-value is `z/2`
29
+
* - The `apply` method is not necessary for pattern matching. It is only used to mimick a constructor. `val x = Twice(21)` expands to `val x = Twice.apply(21)`.
30
30
*
31
31
* The code in the preceding example would be expanded as follows:
32
32
*
33
-
*
33
+
* {{{
34
34
* object TwiceTest extends Application {
35
35
* val x = Twice.apply(21)
36
36
* Twice.unapply(x) match { case Some(n) => Console.println(n) } // prints 21
37
37
* }
38
-
*
38
+
* }}}
39
39
* The return type of an `unapply` should be chosen as follows:
40
40
*
41
-
* * If it is just a test, return a `Boolean`. For instance `case even()`
42
-
* * If it returns a single sub-value of type `T`, return a `Option[T]`
43
-
* * If you want to return several sub-values `T1,...,Tn`, group them in an optional tuple `Option[(T1,...,Tn)]`.
41
+
* - If it is just a test, return a `Boolean`. For instance `case even()`
42
+
* - If it returns a single sub-value of type `T`, return a `Option[T]`
43
+
* - If you want to return several sub-values `T1,...,Tn`, group them in an optional tuple `Option[(T1,...,Tn)]`.
44
44
*
45
45
* Sometimes, the number of sub-values is fixed and we would like to return a sequence. For this reason, you can also define patterns through `unapplySeq`. The last sub-value type `Tn` has to be `Seq[S]`. This mechanism is used for instance in pattern `case List(x1, ..., xn)`.
0 commit comments