简体   繁体   中英

Scala How To Send Anonymous Functions Results as Argument

How does one send the result of an anonymous function as an argument into another function?

As an example:

object TestThisFunction {

  def getString(): String = {
    "foo"
  }

  def useString(foo: String) = {
      println(foo + "bar")
  }

  useString("foo");
  useString(getString());

  // This does not work: type mismatch; found : () => String required: String
  useString(() => {
    "foo"  
  })
}

Is there some syntax that would make the last call to useString() work using an anonymous function?

Thank you for your time.

Call the anonymous function immediately after creating it, to have it's evaluated value be used, instead of the function itself:

useString((() => {
  "foo"  
})())

You can also pass in arguments, if needed:

scala> ((a: String) => { a })("bar")
res3: String = bar

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