简体   繁体   中英

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?

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>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM