MOCKSTACKS
EN

# Scala Extractors

## Examples

#### Tuple Extractors

x and y are extracted from the tuple:

``````val (x, y) = (1337, 42)
// x: Int = 1337
// y: Int = 42``````

To ignore a value use _:

``````val (_, y: Int) = (1337, 42)
// y: Int = 42``````

To unpack an extractor:

``````val myTuple = (1337, 42)
myTuple._1 // res0: Int = 1337
myTuple._2 // res1: Int = 42``````

Note that tuples have a maximum length of 22, and thus ._1 through ._22 will work (assuming the tuple is at least that size).

Tuple extractors may be used to provide symbolic arguments for literal functions:

``````val persons = List("A." -> "Lovelace", "G." -> "Hopper")
val names = List("Lovelace, A.", "Hopper, G.")
assert {
names ==
(persons map { name =>
s"\${name._2}, \${name._1}"
})
}
assert {
names ==
(persons map { case (given, surname) =>
s"\$surname, \$given"
})
}``````

#### Case Class Extractors

A case class is a class with a lot of standard boilerplate code automatically included. One benefit of this is that Scala makes it easy to use extractors with case classes.

``````case class Person(name: String, age: Int) // Define the case class
val p = Person("Paola", 42) // Instantiate a value with the case class type
val Person(n, a) = p // Extract values n and a
// n: String = Paola
// a: Int = 42``````

At this juncture, both n and a are vals in the program and can be accessed as such: they are said to have been 'extracted' from p. Continuing:

``````val p2 = Person("Angela", 1337)
val List(Person(n1, a1), Person(_, a2)) = List(p, p2)
// n1: String = Paola
// a1: Int = 42
// a2: Int = 1337``````

Here we see two important things:

• Extraction can happen at 'deep' levels: properties of nested objects can be extracted.

•Not all elements need to be extracted. The wildcard _ character indicates that that particular value can be anything, and is ignored. No val is created.

In particular, this can make matching over collections easy:

``````val ls = List(p1, p2, p3) // List of Person objects
ls.map(person => person match {
case Person(n, a) => println("%s is %d years old".format(n, a))
})``````

Here, we have code that uses the extractor to explicitly check that person is a Person object and immediately pull out the variables that we care about: n and a.

## Conclusion

In this page (written and validated by ) you learned about Scala Extractors . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala For Expressions.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.