4

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 _ => ???
}
jwinandy
  • 1,739
  • 12
  • 22

2 Answers2

9

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)
Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
4

You could declare it as a PartialFunction so that you could use the case-block directly. This works because a block of cases 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"))
dhg
  • 52,383
  • 8
  • 123
  • 144