Is there way to match strings in scala like this:
def matcher(arg: String) : Expr = {
case left :: '*' :: right => new Binary("*", left, right)
case left :: '+' :: right => new Binary("+", left, right)
}
where left and right are have type String?
Pattern matching is a powerful feature of the Scala language. It allows for more concise and readable code while at the same time providing the ability to match elements against complex patterns.
Pattern matching is the second most widely used feature of Scala, after function values and closures. Scala provides great support for pattern matching, in processing the messages. A pattern match includes a sequence of alternatives, each starting with the keyword case.
Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. It is a more powerful version of the switch statement in Java and it can likewise be used in place of a series of if/else statements.
case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .
You can achieve your goal by matching on regular expressions.
trait Expr
case class Binary(op: String, leftOperand: String, rightOperand: String) extends Expr
val mulPattern = "(\\d*)\\*(\\d*)".r
val addPattern = "(\\d*)\\+(\\d*)".r
def matcher(arg: String) : Expr = {
arg match {
case mulPattern(left, right) => new Binary("*", left, right)
case addPattern(left, right) => new Binary("+", left, right)
}
}
def main(args: Array[String]): Unit = {
println(matcher("1+2")) // Binary("+", "1", "2")
println(matcher("3*4")) // Binary("*", "3", "4")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With