You can also do this with extractors:
object Mult { def unapply(x: String): Option[(String, String)] = x.split("\\*") match { case Array(a: String, b: String) => Some(a -> b) case _ => None } } object Add { def unapply(x: String): Option[(String, String)] = x.split("\\+") match { case Array(a: String, b: String) => Some(a -> b) case _ => None } } def matcher(arg: String) = arg match { case Mult(left, right) => Binary("*", left, right) case Add(left, right) => Binary("+", left, right) case _ => println("not matched") }
You can also apply the apply method for each extractor, for example:
def apply(l: String, r: String) = s"$l*$r"
but this is optional
source share