How to avoid to wrap args when implementing a def with pattern matching ?
Examples :
def myDef(a: A, b:B, c: C): D = (a,c,d) match {
case ('qsdqsd, _ , _ ) => ???
case _ => ???
}
You can take the tuple as the function argument instead:
def myDef(abc: (A,B,C)): D = abc match {
case ('qxpf, _, _) => ???
case _ => ???
}
Users will have their non-tuple argument lists automatically promoted into tuples. Observe:
scala> def q(ab: (Int,String)) = ab.swap
q: (ab: (Int, String))(String, Int)
scala> q(5,"Fish")
res1: (String, Int) = (Fish,5)
You could declare it as a PartialFunction
so that you could use the case
-block directly. This works because a block of case
s is a PartialFunction in Scala.
val myDef: PartialFunction[(A, B, C), D] = {
case ("qsdqsd", b, c) => b + c
case _ => "no match"
}
println(myDef("qsdqsd", "b", "c"))
println(myDef("a", "b", "c"))
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