Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating objects on both sides of assignment operator in Scala; how does it work

Tags:

syntax

scala

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.)

like image 882
Stijn Avatar asked Nov 29 '22 08:11

Stijn


1 Answers

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).

like image 195
pme Avatar answered Dec 05 '22 11:12

pme