I want to understand the mechanism behind the following line:
val List(x) = Seq(1 to 10)
What is the name of this mechanism? Is this the same as typecasting, or is there something else going on? (Tested in Scala 2.11.12.)
The mechanism is called Pattern Matching.
Here is the official documentation: https://docs.scala-lang.org/tour/pattern-matching.html
This works also in for comprehensions:
for{
People(name, firstName) <- peoples
} yield s"$firstName $name"
To your example:
val List(x) = Seq(1 to 10)
x
is the content of that List - in your case Range 1 to 10
(You have a list with one element).
If you have really a list with more than one element, that would throw an exception
val List(x) = (1 to 10).toList // -> ERROR: undefined
So the correct pattern matching would be:
val x::xs = (1 to 10).toList
Now x
is the first element (head) and xs
the rest (tail).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With