1

Is it possible in Scala to do pattern matching with an operator? I want to input a tuple, for example ("Hello World", +) or ("Good Afternoon", /) and do different actions for different operators, like:

mytuple match {
  case (SomeRegex(str), +) => println(str + " the same")
  case (SomeRegex(str), /) => println(str + " but different")
}

How can I correctly do this? I don't care what the operators do, I just want them as a kind of environment.

Maybe even passing the char +or / along is considered best practice, but I hardly believe it.

1 Answer 1

1

Where would the + and * be coming from? And what would the type of mytuple be?

Depending on your answer to those, this might be a reasonable answer.

The language doesn't really expose * and + as objects (at least not in the way it seems like you're aiming for).

sealed trait Op
case object `+` extends Op
case object `*` extends Op
// ...

With those definitions in hand...

def dispatch(mytuple: (String, Op)): Unit =
  mytuple match {
    case (SomeRegex(str), `+`) => println(str + " the same")
    case (SomeRegex(str), `*`) => println(str + " but different")
    case _ => ()
  }

You can treat + and * (or any other string that the parser might have treated otherwise: def type class some identifier with spaces) as regular identifiers by wrapping them in `'s.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.