如何在实现带模式匹配的def时避免包装args?
示例:
def myDef(a: A, b:B, c: C): D = (a,c,d) match {
case ('qsdqsd, _ , _ ) => ???
case _ => ???
}
答案 0 :(得分:9)
您可以将元组作为函数参数:
def myDef(abc: (A,B,C)): D = abc match {
case ('qxpf, _, _) => ???
case _ => ???
}
用户将其非元组参数列表自动提升为元组。观察:
scala> def q(ab: (Int,String)) = ab.swap
q: (ab: (Int, String))(String, Int)
scala> q(5,"Fish")
res1: (String, Int) = (Fish,5)
答案 1 :(得分:4)
您可以将其声明为PartialFunction
,以便您可以直接使用case
- 块。这是有效的,因为case
s 的块是 Scala中的PartialFunction。
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"))