1

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)

Luciano
  • 2,388
  • 1
  • 22
  • 33
  • 1
    There is an answers to your question below already, but also you can read an answer from the same question that given by Scala-lang developer with explanation [here](http://stackoverflow.com/a/5259946/4804363) – Fellrond Aug 03 '16 at 11:46
  • Yes you're right this is a duplicate of the above; shame I couldn't find it in the search. – Luciano Aug 03 '16 at 14:06
  • Should probably add that it _is_ possible to do `Foo(_, b = 2)` i.e. if the variable argument occurs before any named arguments. – Luciano Aug 03 '16 at 14:07
  • Correct. Only because it expands to `Foo(x => x, b = 2)`, and there is no definitions that cannot be infered by compiler itself :) – Fellrond Aug 03 '16 at 14:10

2 Answers2

1

Syntactically, underscore is bound at the enclosing expression, and assignment is an expression.

So your example expands to Foo(x => a = x, b = 2).

That's done by the parser, before anyone asks if you intended named args.

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

som-snytt
  • 39,429
  • 2
  • 47
  • 129
0

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.

Fellrond
  • 211
  • 1
  • 7