I am in the process of writing a small parsing routine in Scala that uses extractors to simplify parsing. During my research I discovered the conjunction pattern match (Pattern matching with conjunctions (PatternA AND PatternB)) which has been really useful. Using that I have been able to express extractors as below (outline only).
case object & {
def unapply[T](t : T) = Some(t, t)
}
case object ParamA {
def unapply(jsonStr: String) : Option[String] = {
// If param A found in json return a Some(...) else None
???
}
}
case object ParamB {
def unapply(jsonStr: String) : Option[String] = {
// If param B found in json return a Some(...) else None
???
}
}
case object ParamC {
def unapply(jsonStr: String) : Option[String] = {
// If param C found in json return a Some(...) else None
???
}
}
These let me match for mandatory ParamA and ParamB patterns as below.
val jsonStr = "..." // A Json string
jsonStr match {
case ParamA(a) & ParamB(b) => {
// Got a and b. Now do something with it
}
case _ => {
}
}
However, if I want to match mandatory ParamA and ParamB patterns and also optionally a ParamC pattern, how would I go about expressing that in a single line?
val jsonStr = "..." // A Json string
jsonStr match {
case ParamA(a) & ParamB(b) & Optional(ParamC(c)) /* Is this possible? */ => {
// Got a and b and an optional c. Now do something with it
}
case _ => {
}
}