Reputation: 143
I am trying to use Scala's pattern matching feature to check for the type of the first parameter, and to accept any arbitrary type for the second parameter- though I'm not sure syntactically how this works in Scala as I am fairly new, and I cannot find anything as to how tuples work with one another in Scala as it relates to pattern matching and case statements.
My initial attempt:
case foo => (eval(e1, e2), eval(e1, e2)) match
{
case (S(e1), _) => (bar(e1, e2) + bar(e1, e2))
case _ => ???
}
Wherein, this should, in this case, check that the first argument is a string, and accept the second to be whatever, and then do whatever bar wants.
Further, I have seen examples like so:
case (_: String, _: Int) => ???
however, I am unclear as to how you reference these parameters in your right hand statement.
What is the proper method of referencing these _ parameters in a statement?
Upvotes: 1
Views: 769
Reputation: 14825
You use :
to enfore the type. Below the example. You can refer to any value using a variable and without explicitly declaring type.
Scala REPL
scala> :paste
// Entering paste mode (ctrl-D to finish)
("Java", 1) match {
case (str: String, v) => println(s"value: $v")
case _ => println("something")
}
// Exiting paste mode, now interpreting.
value: 1
Upvotes: 1