I'm starting to learn the great Scala language ang have a question about "deep" pattern matching
I have a simple Request
class:
case class Request(method: String, path: String, version: String) {}
And a function, that tries to match an request
instance and build a corresponding response:
def guessResponse(requestOrNone: Option[Request]): Response = {
requestOrNone match {
case Some(Request("GET", path, _)) => Response.streamFromPath(path)
case Some(Request(_, _, _)) => new Response(405, "Method Not Allowed", requestOrNone.get)
case None => new Response(400, "Bad Request")
}
}
See, I use requestOrNone.get
inside case
statement to get the action Request
object. Is it type safe, since case
statement matched? I find it a bit of ugly. Is it a way to "unwrap" the Request
object from Some
, but still be able to match Request
class fields?
What if I want a complex calculation inside a case
with local variables, etc... Can I use {}
blocks after case
statements? I use IntelliJ Idea with official Scala plugin and it highlights my brackets, suggesting to remove them.
If that is possible, is it good practice to enclose matches in matches?
... match {
case Some(Request("GET", path, _)) => {
var stream = this.getStream(path)
stream match {
case Some(InputStream) => Response.stream(stream.get)
case None => new Response(404, "Not Found)
}
}
}