Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid syntax overhead for def definition with pattern matching in Scala?

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 _ => ???
}
like image 894
jwinandy Avatar asked Dec 11 '22 22:12

jwinandy


2 Answers

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)
like image 56
Rex Kerr Avatar answered May 18 '23 15:05

Rex Kerr


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"))
like image 42
dhg Avatar answered May 18 '23 15:05

dhg