Luciano Luciano - 1 year ago 180
Scala Question

Partial application with named parameters

If I use partial application on a method (the

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download