“Any does not take parameters” - storing Unit func

2019-09-04 05:06发布

问题:

I am trying to store a function in my actions HashMap. I want this function to be readf("coffee", 1, doTest)

Currently I get an error trying to execute the last line,

"Any does not take parameters". How do I store a function into a HashMap, then call it at a later time?

var xx = 0

val values = new HashMap[String, Int]
values += "coffee" -> 2
println(values("coffee"))

val actions = new HashMap[String, Any]

def readf(valueName: String, sufficient: Int, f: () => Unit): Unit = 
  if (values(valueName) > sufficient) f() else ()

  def doTest(): Unit = {
    xx == xx + 1
    println(xx)
  }

  actions += "check_cup" -> readf("coffee", 1, doTest)

  actions("check_cup")()

回答1:

To store a function of type () => Unit in your actions map you should declare the the type to be HashMap[String, () => Unit].

Looking at your code, it looks like readf has a return value of Unit so:

actions += "check_cup" -> readf("coffee", 1, doTest)

is actually trying to put a mapping of "check_cup" -> Unit into the map. This is most likely not what you want. You probably want:

def readf(valueName: String, sufficient: Int, f:() => Unit): () => Unit = 
    if (values(valueName) > sufficient) f else () => Unit


回答2:

When you do:

actions += "check_cup" -> readf("coffee", 1, doTest)

you're already evaluating the function readf and storing the "result" of Unit rather than storing the function. You want that to be:

actions += "check_cup" -> () => readf("coffee", 1, doTest)

Then you're storing a function that takes no parameters, and when it is called, just calls readf with the params you supplied.

And change the type of actions to Map[String, () => Unit]



标签: java scala