How to avoid the overhead of syntax for def def using pattern matching in Scala?

How to avoid args wrapping when implementing def with pattern matching?

Examples:

def myDef(a: A, b:B, c: C): D = (a,c,d) match { case ('qsdqsd, _ , _ ) => ??? case _ => ??? } 
+4
source share
2 answers

Instead, you can take a tuple as an argument to a function:

 def myDef(abc: (A,B,C)): D = abc match { case ('qxpf, _, _) => ??? case _ => ??? } 

Users will have their argument lists without tuples, automatically promoted to tuples. Note:

 scala> def q(ab: (Int,String)) = ab.swap q: (ab: (Int, String))(String, Int) scala> q(5,"Fish") res1: (String, Int) = (Fish,5) 
+9
source

You can declare it as a PartialFunction so you can use case -block directly. This works because the case block 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")) 
+4
source

Source: https://habr.com/ru/post/1436435/


All Articles