Bob
Bob

Reputation: 8504

Explain these lines of code in Scala

I'm trying to understand exactly how the following code snippet works, in particular line 2, Seq(JsString(bar), _*), and line 3, must_, syntax is puzzling to me

val foo = (Json.parse(contentAsString(result)    
val Seq(JsString(bar), _*) = (foo \\ "bar")
bar must_== "crazy"

Upvotes: 0

Views: 297

Answers (1)

Rex Kerr
Rex Kerr

Reputation: 167911

Line 2 is a pattern match, but using val syntax. foo \\ "bar" returns a Seq, which you can match on;

Seq(JsString(bar), _*)

means that the item must match to a Seq and the first item must be a JsString whose content we will call bar, and we don't care about the rest (_*). Normally you'd see this like so:

(foo \\ "bar") match {
  case Seq(JsString(bar), _*) =>  // do something with bar
  ...
}

but it turns out that you can initialize vals this way also.

Also, must_== is a method name (methods can be alphanumeric followed by an underscore followed by symbols) for some testing framework. I forget which. But there almost certainly is an implicit conversion from whatever to tested-whatever, and tested-whatever has the must_== method.

Upvotes: 7

Related Questions