Assigning value to arg with val object(arg) = object

Viewed 42

I am following this tutorial on GraphQL with Sangria. I am wondering about the following line

val JsObject(fields) = requestJSON

where requestJSON is an object of JsValue. This way of assigning fields is new to me and my question is, if you could name that pattern or provide me with a link to a tutorial regarding this structure.

2 Answers

It is the Extractor pattern, you can reach the same result implementing the unapply method on your arbitrary object (like shown in the example). When you create a case class the compiler produces an unapply method for you, so you can do:

case class Person(name : String, surname : String)
val person = Person("gianluca", "aguzzi")
val Person(name, surname) = person

The important thing to know is that val definitions support a Pattern on the left-hand side of the assignment, thus providing (subset of the functionality of) Pattern Matching.

So, your example is equivalent to:

val fields = requestJSON match {
  case JsObject(foo) => foo
}

See Scala Language Specification Section 4.1 Value Declarations and Definitions for details.

So, for example, if you have a list l and you want to assign the first element and the rest, you could write:

val x :: xs = l

Or, for the fairly common case where a method returns a tuple, you could write:

val (result1, result2) = foo()
Related