How to use named parameters with curried function in scala

I have a method with 4 parameters that is used in blocks. Inside each block, the first parameter is always the same:

// Block 1 - first parameter always "A" foo(a="A", b="x", c="y", d="z") foo(a="A", b=".", c=",", d="-") foo(a="A", b="1", c="2", d="3") // Block 2 - first parameter always "B" foo(a="B", b="x", c="y", d="z") foo(a="B", b=".", c=",", d="-") foo(a="B", b="1", c="2", d="3") 

I need a quick way to create a method for each block, so I only need to specify the other 3 parameters. Currently I can do this:

 def fooCurried(a: String) = foo(a, _: String, _: String, _: String) val fooA = fooCurreid("A") fooA("x", "y", "z") fooA(".", ",", "-") fooA("1", "2", "3") val fooB = fooCurried("B") fooB("x", "y", "z") fooB(".", ",", "-") fooB("1", "2", "3") 

The problem with this approach is that I am losing my named parameters. They become v1 , v2 and v3 . The use of these parameters is important in this case, because the types of the remaining 3 parameters are the same, so they are easy to mix.

Is there an easy way to define the fooCurried function as described above, which I can easily use in different contexts, but allows me to use named parameters?

I would like something that I can use as follows:

 def fooCurried(a: String) = ??? val fooA = fooCurreid("A") fooA(b="x", c="y", d="z") fooA(b=".", c=",", d="-") fooA(b="1", c="2", d="3") 

Thanks in advance!

+5
source share
2 answers

How about this:

 case class fooCurried(a: String) { def apply(b: String, c: String, d: String) = { // do something println(a + "," + b + "," + c + "," + d) } } 

You can use it as follows:

 scala> val fooA = fooCurried(a = "A") fooA: fooCurried = fooCurried(A) scala> fooA(b="B", c="C", d="D") A,B,C,D scala> fooA(b="x", c="y", d="z") A,x,y,z 
+4
source

One alternative way to use case class :

 case class Foo(a:String, b:String, c:String) val f = Foo(a="a", b="b", c="c") foo(f.copy(b ="b1", c="c1")) 

But then your foo will take the class as an argument instead of 4 multiple lines.

+1
source

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


All Articles