Same koan as above, but we are pattern matching a list with only one item!
To obtain the second element you can expand on the pattern.
To obtain the second element you can expand on the pattern. Where x
is the first element, y
is the second element, and xs
is the rest:
To pattern match against List
, you can also establish a pattern match if you know the exact number of elements in a List
:
To pattern match against a List
, the list can be split into parts, in this case the head x
and the tail xs
.
To pattern match against a List
, the list can be split into parts, in this case the head x
and the tail xs
. Since the case doesn't terminate in Nil
, xs
is interpreted as the rest of the list:
If a pattern is exactly one element longer than a List
, it extracts the final Nil
:
Pattern matching can match complex expressions:
A backquote can be used to refer to a stable variable in scope to create a case statement - this prevents "variable shadowing":
Scala has a built-in general pattern matching mechanism.
Scala has a built-in general pattern matching mechanism. It allows to match on any sort of data with a first-match policy. Here is a small example which shows how to match against an integer value:
object MatchTest1 extends App { def matchTest(x: Int): String = x match { case 1 => "one" case 2 => "two" case _ => "many" // case _ will trigger if all other cases fail. } println(matchTest(3)) // prints "many" }
The block with the case
statements defines a function which maps integers to strings. The match
keyword provides a convenient way of applying a function (like the pattern matching function above) to an object.
Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes
.
Scala also allows the definition of patterns independently of case classes, using unapply
methods in extractor objects.
Pattern matching returns something:
Pattern matching can return complex values:
A backquote can be used to refer to a method parameter as a stable variable to create a case statement:
Pattern matching can substitute parts of expressions:
Pattern matching can wildcard parts of expressions:
The parameterless execute method has been deprecated and will be removed in a future version of ScalaTest. Please invoke execute with empty parens instead: execute().
The trap method is no longer needed for demos in the REPL, which now abreviates stack traces, and will be removed in a future version of ScalaTest