Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: not a legal formal parameter

I have a function:

val ADD = (x: Double, y Double) => x+y

and I want to put this in a map, the following seems to work

val nameMap = Map(ADD -> "+")

but this doesn't:

val diffMap = Map(
 ADD -> (x: AlgObj,y: AlgObj, xdif: AlgObj, ydif: AlgObj) =>
  new AlgObj(ADD, xdif, ydif))

nor does various other things that I have tried, always with the message: 'not a legal formal parameter' with the caret under the '->'. Anyone know what this error message means?

like image 241
Lucas Avatar asked Jan 24 '26 08:01

Lucas


1 Answers

I got the same error message when I pasted in your first line of code without correcting the error in it:

scala> val ADD = (x: Double, y Double) => x+y
<console>:1: error: not a legal formal parameter
       val ADD = (x: Double, y Double) => x+y
                               ^

I went on to try this:

scala> val ADD = (x: Double, y: Double) => x+y
ADD: (Double, Double) => Double = <function>

scala> val diffMap = Map(ADD -> (x: String, y: String) => x + y)
<console>:1: error: not a legal formal parameter
       val diffMap = Map(ADD -> (x: String, y: String) => x + y)
                             ^

So it looks like this error indicates an invalid function parameter, and the parser is trying to group Map(ADD -> (x: String, y: String) => x + y) like Map((ADD -> (x: String, y: String)) => x + y).

So you need to put parentheses or braces around the function:

scala> val diffMap = Map(ADD -> ((x: String, y: String) => x + y))
diffMap: scala.collection.immutable.Map[(Double, Double) => Double,(String, String) => java.lang.String] = Map(<function> -> <function>)
like image 115
Rachel Shallit Avatar answered Jan 27 '26 01:01

Rachel Shallit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!