Wednesday, March 14, 2018

An easier way to interpret code blocks and curly braces in Scala

I recently realized a nifty way for reading a particular piece of Scala syntax that has always confused me.

Basically how to interpret code that makes use of curly braces when calling functions with multiple parameter lists or code that makes use of {} in place of () when acceptable.

Basically, code that looks like this:

foo() {
  val a = "Hello"
  val b = "world"
  s"$a $b"
}

or

foo() { (x:Int) =>
  val y = x * 2
  println(s"output is: $y")
}

Or a snippet of code defining a controller method using the play framework:

Action.async(action.parser) { request =>
  Logger.info("Calling action")
  action(request)
}

Or some slightly modified code from a code base at work:

extractActiveMembershipFromRequest(membershipKey) { requesterId =>
...some code here...
}

Or another slightly modified code from work:

secure.hasRequiredRole(user, role) {
submitRequest(user)
}