Luciano Luciano - 4 months ago 14
Scala Question

Partial application with named parameters

If I use partial application on a method (the

apply()
method of my case class here), it works:

case class Foo(a : Int, b : Int)

val pf : Int => Foo = Foo(_ ,2)


However, it doesn't appear to be possible to use this in combination with named parameters, e.g. :

case class Foo(a : Int, b : Int)

val pf : Int => Foo = Foo(a = _ ,b = 2)


it results in :

Error:(7, 33) not found: value a
lazy val pf : Int => Foo = Foo(a = _ ,b = 2)
^


Is there any way around this? I need this because I have case classes with a large number of default parameters, that I don't want to have to specify most of the time.

(Scala 2.11)

Answer

Unfortunately. you cannot use placeholder syntax to expand function this way. This is because of compiler behavior, it tries to expand undersore to the closest position and then you will have an

val pf : Int => Foo = Foo((x => a = x) ,b = 2)

instead of

val pf : Int => Foo = x => Foo(a = x ,b = 2)

In first example "a" is surely not defined in context of anonymous function and will result an error.

I suggest you to use second example to work with named parameters. Additionally, it's much cleaner in code exceptionally if you accept multiple parameters.